我正在嘗試創建Java死鎖程序。我實時知道,我們不會在線程中創建任何死鎖。不幸的是,我在一次採訪中被要求編寫一個「使用兩個線程的死鎖程序」。所以這裏是創建我自己的Java死鎖程序
package Thread.DeadLock;
public class deadLock2 {
static ThreadSample1 t1 = new ThreadSample1();
static ThreadSample2 t2 = new ThreadSample2();
public static void main(String args[]) {
t1.start();
t2.start();
}
public static class ThreadSample1 extends Thread {
public void run() {
System.out.println("In first run method");
try {
System.out.println("Holding lock in first one");
synchronized (t1) {
System.out.println("t1 going to wait for t2");
t1.wait();
System.out.println("t1 finished for waiting");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static class ThreadSample2 extends Thread {
public void run() {
System.out.println("In second run method");
try {
System.out.println("Holding lock for second one");
synchronized (t2) {
System.out.println("t2 going to wait for t1");
t2.wait();
System.out.println("t2 finished for waiting");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
我可以看到程序卡住了。我假設它處於僵局。 t1.start()等待t2完成其任務,t2.start()等待t1完成其任務。現在,當我嘗試通過使用t1.notify()通知等待的線程來消除死鎖時,我得到IllegalMonitorStateException。 有人可以告訴在這種情況下如何消除死鎖而不會造成任何情況。
你爲什麼要引用t1和t2變量?你不應該通過使用引用來明確地處理線程。 – mlewandowski
你的代碼是否表現出[4對於死鎖的必要和充分的要求](http://nob.cs.ucdavis.edu/classes/ecs150-1999-02/dl- cond.html)? (我認爲它只展示了這裏列出的前3個)。 –