效果,两个线程一直在互相等待 代码
public class DeadLockDemo {
public static void main ( String [ ] args) {
Map map = new HashMap < > ( 16 ) ;
List list = new ArrayList < > ( ) ;
new Data1 ( map, list) . start ( ) ;
new Data2 ( map, list) . start ( ) ;
}
}
class Data1 extends Thread {
private Map map;
private List list;
public Data1 ( Map map, List list) {
this . map = map;
this . list = list;
}
@Override
public void run ( ) {
synchronized ( map) {
System . out. println ( Thread . currentThread ( ) . getName ( ) + "获得了map资源,现在往下需要list资源" ) ;
try {
TimeUnit . SECONDS. sleep ( 2 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
synchronized ( list) {
System . out. println ( "死锁1" ) ;
}
}
}
}
class Data2 extends Thread {
private Map map;
private List list;
public Data2 ( Map map, List list) {
this . map = map;
this . list = list;
}
@Override
public void run ( ) {
synchronized ( list) {
System . out. println ( Thread . currentThread ( ) . getName ( ) + "获得了list资源,现在往下需要map资源" ) ;
synchronized ( map) {
System . out. println ( "死锁2" ) ;
}
}
}
}