package project;

public class Main implements Runnable{
    static Object s1 = new Object(),s2 = new Object();
    
    public void run(){
        if(Thread.currentThread().getName().equals("t1")){
            synchronized (s1) {
                System.out.println("th1 locked s1");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
                synchronized (s2) {
                    System.out.println("th1 locked s2");
                }
                
            }
        }else {
            synchronized (s2) {
                System.out.println("th1 locked s2");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
                synchronized (s1) {
                    System.out.println("th1 locked s1");
                }
            }
        }
    }
    public static void main(String[] args) {
        Thread t1 = new Thread(new Main(),"t1");
        Thread t2 = new Thread(new Main(),"t2");
        t1.start();
        t2.start();
    }
}

 

相关文章:

  • 2021-05-20
  • 2022-12-23
  • 2021-11-17
  • 2021-10-28
  • 2021-08-05
  • 2021-05-18
  • 2022-12-23
猜你喜欢
  • 2021-09-16
  • 2021-07-06
  • 2022-02-03
  • 2022-12-23
  • 2021-08-20
  • 2022-12-23
  • 2021-07-02
相关资源
相似解决方案