手记

Java线程死锁代码示例

public class DeadLockDemo {

    public static void main(String[] args) {
        final Object lock1 = new Object();
        final Object lock2 = new Object();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock1){
                    System.out.println(Thread.currentThread().getName() + "锁住了lock1");
                    try {
                        Thread.sleep(5000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lock2){
                        System.out.println(Thread.currentThread().getName() + "锁住了lock2");
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock2){
                    System.out.println(Thread.currentThread().getName() + "锁住了lock2");
                    try {
                        Thread.sleep(5000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lock1){
                        System.out.println(Thread.currentThread().getName() + "锁住了lock1");
                    }
                }
            }
        }).start();

    }
}

/**
 * jstack PID结果:
 * Found one Java-level deadlock:
 * =============================
 * "Thread-1":
 *   waiting to lock monitor 0x0000000018103568 (object 0x00000000d5f36038, a java.lang.Object),
 *   which is held by "Thread-0"
 * "Thread-0":
 *   waiting to lock monitor 0x0000000018100cd8 (object 0x00000000d5f36048, a java.lang.Object),
 *   which is held by "Thread-1"
 *
 * Java stack information for the threads listed above:
 * ===================================================
 * "Thread-1":
 *         at org.example.thread.死锁$2.run(死锁.java:35)
 *         - waiting to lock <0x00000000d5f36038> (a java.lang.Object)
 *         - locked <0x00000000d5f36048> (a java.lang.Object)
 *         at java.lang.Thread.run(Thread.java:748)
 * "Thread-0":
 *         at org.example.thread.死锁$1.run(死锁.java:19)
 *         - waiting to lock <0x00000000d5f36048> (a java.lang.Object)
 *         - locked <0x00000000d5f36038> (a java.lang.Object)
 *         at java.lang.Thread.run(Thread.java:748)
 *
 * Found 1 deadlock.
 */


1人推荐
随时随地看视频
慕课网APP