我是想實現一些基本的啓動,停止,暫停和恢復功能,可以讓我下面的狀態轉換:Java線程的原因死鎖
- 停止運行
- 運行到停止
- 運行以暫停
- 暫停運行
- 停下來,停止(原因死鎖)
大多數情況下按預期運行,但最後的狀態轉換不可行,因爲它會使線程凍結。有人能解釋我爲什麼會發生這種情況,以及如何預防這種情況?下面是代碼的相關部分:
public class ThreadTest implements Runnable {
private volatile boolean running = false;
private volatile boolean paused = false;
private Thread thread;
public ThreadTest() {
thread = new Thread(this);
}
public void run() {
while (running) {
try {
if (paused) {
synchronized (this) {
while (paused)
wait();
}
}
}
catch (InterruptedException e) {
}
}
}
public synchronized void start() {
if(running && !thread.isAlive())
return;
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop() {
if(!running && thread.isAlive())
return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(0);
}
public synchronized void resume() {
if(paused) {
paused = false;
notify();
}
else {
return;
}
}
public synchronized void pause() {
if(!paused) {
paused = true;
}
else {
return;
}
}
}
嘗試調用''中的情況下paused'通知()''中的stop()'方法。你通過wait()調用來鎖定你的線程。 – SeniorJD 2013-05-01 14:53:24
@SeniorJD:請參閱我的答案和我對xagyg的評論,爲什麼notify()不能工作。 – brainOverflow 2013-05-02 19:07:20
+1因爲你的問題對我有用(讓我覺得)! – brainOverflow 2013-05-02 19:10:04