一个拿到o1对象准备去拿o2,另一个拿到o2对象准备去拿o1;
你写的代码意思是:
第一个拿到o1后,锁住o1,sleep 5秒,释放o1,去取o2
第二个拿到o2后,锁住o2,sleep 5秒,释放o2,去取o1;
那么,不管是谁睡5秒后,都会释放掉自己手里的锁的,
改成如下代码:
public class TestDeadLock implements Runnable {
public int flag = 2;
static Object o1 = new Object();
static Object o2 = new Object();
public void run() {
if (flag == 1) {
synchronized (o1) {
System.out.println("锁住o1");
// Thread.currentThread().interrupt(); //如果任意一个线程打断的话,就会运行到结束
synchronized (o2) { //不用加sleep(5000)
System.out.println("1"); //这样的代码才是锁住o1,想要获得o2
} }
}
// 疑问:无法死锁
if (flag == 0) {
synchronized (o2) {
System.out.println("锁住o2");
synchronized (o1) { //这样的代码才是锁住o2,想要获得o1
System.out.println("2");
} }
}
}
public static void main(String[] args) {
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
}
|