class MyThread implements Runnable{
    private Object o1 = new Object();
    private Object o2 = new Object();
    private boolean flag = true;

    public void run(){
        if(flag){
            flag = false;
            synchronized(o1){
                System.out.println(Thread.currentThread().getName() + "---have o1");
                try{
                    Thread.sleep(100);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
                synchronized(o2){
                    System.out.println(Thread.currentThread().getName() + "---have o2");
                }
            }
        }else{
            flag = true;
            synchronized(o2){
                System.out.println(Thread.currentThread().getName() + "---have o2");
                try{
                    Thread.sleep(100);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
                synchronized(o1){
                    System.out.println(Thread.currentThread().getName() + "---have o1");
                }
            }
        }
    }
}

public class DeadLock{
    public static void main(String[] args){
        MyThread my = new MyThread();
        new Thread(my, "Thread-a").start();
        new Thread(my, "Thread-b").start();
    }
}

相关文章:

  • 2021-12-09
  • 2021-08-23
  • 2022-12-23
  • 2021-11-30
  • 2021-11-03
  • 2022-02-27
  • 2021-10-05
猜你喜欢
  • 2022-01-13
  • 2022-12-23
  • 2022-01-29
  • 2021-08-04
  • 2022-12-23
  • 2022-03-09
  • 2021-07-05
相关资源
相似解决方案