小村村长

导航

多线程死锁

public class 线程安全_死锁 {
    public static void main(String[] args) throws InterruptedException {
        Object o1 = new Object();//一号锁
        Object o2 = new Object();//二号锁
        new Thread(()->{
            synchronized (o1){//获取o1锁
                try {
                    Thread.sleep(1000);
                    synchronized (o2){//获取o2锁
                        System.out.println("线程1执行");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(()->{
            synchronized (o2){//获取o2锁
                try {
                    Thread.sleep(1000);
                    synchronized (o1){//获取o1锁
                        System.out.println("线程2执行");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

 

posted on 2022-04-21 16:57  小村村长  阅读(17)  评论(0编辑  收藏  举报