package leo.wan.test.thread;

public class TestDeath {
    public static void main(String[] args) {
        DeathWorker worker = new DeathWorker();
        new Thread(){
            @Override
            public void run() {
                try {
                    worker.lock2WantLock1();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                try {
                    worker.lock1WantLock2();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
package leo.wan.test.thread;

public class DeathWorker {
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();
    public void lock1WantLock2() throws InterruptedException {
        synchronized (lock1){
            Thread.sleep(10000L);
            System.out.println(Thread.currentThread().getName()+"占领了lock1,等待lock2");
            lock2WantLock1();
        }
    }
    public void lock2WantLock1() throws InterruptedException {
        synchronized (lock2){
            Thread.sleep(10000L);
            System.out.println(Thread.currentThread().getName()+"占领了lock2等待lock1");
            lock1WantLock2();
        }
    }
}

 

 posted on 2020-04-15 21:29  改变一下  阅读(163)  评论(0编辑  收藏  举报