最近我訪問了一些面試。採訪者要求我寫保證的死鎖。如何通過wait/notify寫保證死鎖
我已經寫了以下內容:
public class DeadLockThreadSleep {
private static class MyThread implements Runnable {
private Object o1;
private Object o2;
@Override
public void run() {
try {
test(o1, o2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public MyThread(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
public void test(Object o1, Object o2) throws InterruptedException {
synchronized (o1) {
System.out.println("1.acquired: " + o1);
Thread.sleep(1000);
synchronized (o2) {
System.out.println("2.acquired: " + o2);
}
}
}
}
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
new Thread(new MyThread(o1, o2)).start();
new Thread(new MyThread(o2, o1)).start();
}
}
然後他問,如果我確信它是guaranted。我重新記住了Thread.sleep沒有任何保證。
然後我寫了這個代碼:
public static void main(String[] args) {
final Thread mainThread = Thread.currentThread();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
mainThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
這個答案被接受。
他還要求通過等待/通知寫模擬。我想了很多,我無法想象如何寫這個。
可能嗎?
http://stackoverflow.com/questions/19908498/deadlocks-using-wait-and-notify – assylias
@assylias我讀過這個話題。在最高票選答案不是答案 – gstackoverflow