[url=http://hi.baidu.com/lovebwf/blog/item/a3b34781c2ecc0dcbc3e1e93.html]原文链接[/url]
public class DeadLock implements Runnable {
private boolean flag;
static Object o1 = new Object(), o2 = new Object();
public void run() {
System.out.println(flag);
if (flag) {
synchronized (o1) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println("AAA");
}
}
} else {
synchronized (o2) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println("BBB");
}
}
}
}
public static void main(String[] args) {
DeadLock aaa = new DeadLock();
DeadLock bbb = new DeadLock();
aaa.flag = true;
bbb.flag = false;
Thread thA = new Thread(aaa);
Thread thB = new Thread(bbb);
thA.start();
thB.start();
}
}