继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Java线程死锁代码示例

CodeFarmer鲍帅
关注TA
已关注
手记 2
粉丝 0
获赞 1
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.
 */


打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP