线程的死锁

代码来源于《并发编程之美》

public class deadlock {


private static Object resources1 = new Object();

private static Object resources2 = new Object();


public static void main( String [] args ){

new Thread(()->{
synchronized (resources1){
System.out.println(Thread.currentThread()+"get resources1");

try{
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

System.out.println(Thread.currentThread()+" waitting get resources2");

synchronized ( resources2 ){
System.out.println(Thread.currentThread()+"get resources2");
}
}
},"线程1").start();

new Thread(()->{
synchronized (resources2){
System.out.println(Thread.currentThread()+"get resources2");

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

System.out.println(Thread.currentThread()+" waitting get resources1");

synchronized (resources1){
System.out.println(Thread.currentThread()+"get resources1");
}

}
},"线程2").start();
}

}

运行结果

Thread[线程1,5,main]get resources1
Thread[线程2,5,main]get resources2
Thread[线程1,5,main] waitting get resources2
Thread[线程2,5,main] waitting get resources1