码迷,mamicode.com
首页 > 其他好文 > 详细

死锁例子

时间:2019-04-15 16:01:46      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:tac   exce   tar   print   ring   ati   new   current   private   

线程T1持有锁A,再去获取锁B,线程T2持有锁B,再去获取锁A,这时候线程T1获取不到锁B,线程T2获取不到锁A,就发生死锁了

public class DeadLock {

    private static final Object lockA = new Object();
    private static final Object lockB = new Object();

    public static void main(String[] args) {

        new Thread(() -> {
            synchronized (lockA) {
                System.out.println(Thread.currentThread().getName() + "获得锁A");
                try {
                    Thread.sleep(2_000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lockB) {
                    System.out.println(Thread.currentThread().getName() + "获得锁B");
                }
            }
        }, "【线程一】").start();

        new Thread(() -> {
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "获得锁B");
                try {
                    Thread.sleep(2_000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lockA) {
                    System.out.println(Thread.currentThread().getName() + "获得锁A");
                }
            }
        }, "【线程二】").start();

    }

}

 

死锁例子

标签:tac   exce   tar   print   ring   ati   new   current   private   

原文地址:https://www.cnblogs.com/moris5013/p/10710839.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!