同步死锁代码publicclassCounter{staticStringo1="obj1";静态字符串o2="obj2";publicstaticvoidmain(String[]args){Countercounter=newCounter();计数器.add();计数器.dec();}publicvoidadd(){newThread(()->{while(true){synchronized(o1){//获取lockA的锁System.out.println(1);try{Thread.sleep(3000);//这里等待是为了给B加锁的机会}catch(InterruptedExceptione){e.printStackTrace();}synchronized(o2){//获取lockB的锁System.out.println(2);}//释放lockB的锁}//释放lockA的锁}}).start();}publicvoiddec(){newThread(()->{while(true){synchronized(o2){//获取lockB的锁System.out.println(3);尝试{Thread.sleep(3000);//在这里等待是为了给B一个锁定的机会}catch(InterruptedExceptione){e.printStackTrace();}synchronized(o1){//获取lockA的锁System.out.println(4);}//释放lockA的锁}//释放lockB的锁}}).start();}}因为synchronized会造成死锁,所以引入了reentranlock。
