这个例子的关键在于红色标注的代码,定义的obj1和obj2是静态的,当启动线程时,线程间共用一个obj1和obj2,所以会产生死锁。
public class ThreadTest {
public static void main (String[] arg) {
Thread t1 = new Thread(new DeadLock(true));
Thread t2 = new Thread(new DeadLock(false));
t1.start();
t2.start();
}
}
public class DeadLock implements Runnable{
boolean lockFormer;
private static Object obj1 = new Object();
private static Object obj2 = new Object();
public DeadLock(boolean lockFormer) {
this.lockFormer = lockFormer;
}
@Override
public void run() {
if(this.lockFormer) {
synchronized(obj1) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj2) {
System.out.println("obj2");
}
}
}else {
synchronized (obj2) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj1) {
System.out.println("obj1");
}
}
}
}
}