【发布时间】:2013-05-01 14:43:34
【问题描述】:
我正在尝试实现一些基本的启动、停止、暂停和恢复功能,以允许我进行以下状态转换:
- 停止运行
- 跑到停止
- 运行到暂停
- 暂停运行
- 暂停到停止(导致死锁)
大部分都按预期工作,但最后的状态转换是不可能的,因为它使线程冻结。有人可以解释一下为什么会发生这种情况以及如何预防吗?以下是代码的相关部分:
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()方法中调用notify()。你通过wait()调用锁定了你的线程。 -
@SeniorJD:请参阅我的回答和我对 xagyg 的评论,说明为什么 notify() 不起作用。
-
+1 因为你的问题对我有用(让我思考)!
标签: java multithreading concurrency locking