package thread;

import java.util.concurrent.TimeUnit;

/**
 * Created by 李恒名 on 2017/8/29.
 *
 *  死锁测试，线程1获得A锁之后尝试获得B锁，线程2获得B锁后尝试获得A锁，线程1和线程2即产生死锁。
 */
public class DeadlockTest {
    public static void main(String[] args) {
        Object lockA = new Object();
        Object lockB = new Object();
        new Thread(() -> {
            //线程1获得A锁
            synchronized (lockA){
                System.out.println("Thread 1 get lock A .");
                //增加死锁发生几率
                try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}
                //尝试获得B锁
                System.out.println("Thread 1 try get lock B, waiting...");
                synchronized (lockB){
                    //永远无法获得B锁，所以不会打印出来
                    System.out.println("Thread 1 get lock B .");
                }

            }
        }, "Thread 1").start();
        new Thread(() -> {
            //线程2获得B锁
            synchronized (lockB){
                System.out.println("Thread 2 get lock B .");
                //增加死锁发生几率
                try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}
                //尝试获得A锁
                System.out.println("Thread 2 try get lock A, waiting...");
                synchronized (lockA){
                    //永远无法获得A锁，所以不会打印出来
                    System.out.println("Thread 2 get lock A .");
                }

            }
        }, "Thread 2").start();
    }
}

@@ -104,16 +104,25 @@
 %EF%BC%8C%E7%BA%BF%E7%A8%8B1%E8%8E%B7%E5%BE%97A%E9%94%81
+%EF%BC%88monitor%EF%BC%89
 %E4%B9%8B%E5%90%8E%E5%B0%9D%E8%AF%95%E8%8E%B7%E5%BE%97B%E9%94%81

add > deadlock test