題目
面試官:給你15分鐘,設計一個死鎖,應該問題不大吧
我:。。。。
代碼
public class Test implements Runnable{
private static Object obj1 = new Object();
private static Object obj2 = new Object();
private int flag;
public Test(int flag) {
this.flag = flag;
}
@Override
public void run() {
if(flag == 0) {
synchronized (obj1) {
System.out.println(Thread.currentThread().getName() + "得到了obj1的鎖");
try {
//確保另一個線程能夠獲得obj2的鎖
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj2) {
System.out.println(Thread.currentThread().getName() + "得到了obj2的鎖");
}
}
}else {
synchronized (obj2) {
System.out.println(Thread.currentThread().getName() + "得到了obj2的鎖");
try {
//確保另一個線程能夠獲得obj1的鎖
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj1) {
System.out.println(Thread.currentThread().getName() + "得到了obj1的鎖");
}
}
}
System.out.println(Thread.currentThread().getName() + "運行結束");
}
public static void main(String[] args){
new Thread(new Test(0), "線程一").start();
new Thread(new Test(1), "線程二").start();
}
}
案例分析
線程1獲得了 obj1 的鎖,卻在等待 obj2 的鎖;線程2獲得了 obj2 的鎖,卻在等待 obj1 的鎖,兩個線程只有先獲取對方的鎖才能夠釋放對方所需要的鎖,進入了無限等待的情況,產生了死鎖。