java 实现一个死锁

2018-12-12  本文已影响0人  好奇害死猫o
public class DeadLockDemo {

    private static final String A = "A";

    private static final String B = "B";


    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            synchronized (A){
                System.out.println("A is lock");
                try {
                    Thread.currentThread().sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (B){
                    System.out.println("1");
                }
            }
        },"t1");

        Thread t2 = new Thread(() -> {
           synchronized (B){
               System.out.println("B is lock");
               synchronized (A){
                   System.out.println("2");
               }
           }
        });
        t1.start();
        t2.start();
    }


}


运行结果

A is lock
B is lock

上一篇 下一篇

猜你喜欢

热点阅读