我想分别使用wait()/ notify()应用暂停/恢复线程。 我已反复尝试解决此问题,但无法解决,因此请帮助我并解释为什么notify();。不能使计数器线程可运行:
public class Suspend {
boolean isSuspend = false;
int counter = 0;
synchronized public void suspend() {
isSuspend = true;
System.out.println("The counter was suspended!");
}
synchronized public void resume() {
isSuspend = false;
System.out.println("The counter was resumed :)");
notify();
}
public static void main(String[] args) {
Thread.currentThread().setName("Main Thread");
Suspend suspend = new Suspend();
Thread counterThread = new Thread(new Runnable() {
synchronized public void run() {
while(!suspend.isSuspend) {
System.out.println(suspend.counter++);
try { Thread.sleep(1000); }
catch (InterruptedException e) {}
}
try {
while(suspend.isSuspend)
wait();
}
catch (InterruptedException e) {}
}
}, "Counter Thread");
Thread suspendResumeThread = new Thread(new Runnable() {
synchronized public void run() {
while(true) {
try {
Thread.sleep(5000);
suspend.suspend();
Thread.sleep(5000);
suspend.resume();
} catch (InterruptedException e) {}
}
}
}, "Suspend/Resume Thread");
counterThread.start();
suspendResumeThread.start();
}
}
输出如下:
0
1
2
3
4
The counter was suspended!
The counter was resumed :)
The counter was suspended!
The counter was resumed :)
... and so on.
答案 0 :(得分:1)
问题在于这些行:
while (suspend.isSuspend)
wait();
}
在您的counterThread
可运行文件中。
您等待Runnable
,而不是suspend
对象
您需要在suspend
上进行同步,并在suspend
上调用wait():
synchronized (suspend) {
while (suspend.isSuspend)
suspend.wait();
}
}
此外,您的run
方法不需要同步。
答案 1 :(得分:0)
看看counterThread,它在isSuspend标志的第一次更改时结束。
我认为您需要这样的东西:
public class Suspend {
volatile boolean isSuspend = false;
int counter = 0;
synchronized public void suspend() {
isSuspend = true;
System.out.println("The counter was suspended!");
}
synchronized public void resume() {
isSuspend = false;
System.out.println("The counter was resumed :)");
notify();
}
public static void main(String[] args) {
Thread.currentThread().setName("Main Thread");
Suspend suspend = new Suspend();
Thread counterThread = new Thread(new Runnable() {
synchronized public void run() {
while(true){
while(!suspend.isSuspend) {
System.out.println(suspend.counter++);
try { Thread.sleep(1000); }
catch (InterruptedException e) {}
}
try {
while(suspend.isSuspend)
wait();
}catch (InterruptedException e) {}
}
}
}
}, "Counter Thread");
Thread suspendResumeThread = new Thread(new Runnable() {
synchronized public void run() {
while(true) {
try {
Thread.sleep(5000);
suspend.suspend();
Thread.sleep(5000);
suspend.resume();
} catch (InterruptedException e) {}
}
}
}, "Suspend/Resume Thread");
counterThread.start();
suspendResumeThread.start();
}
最后,您还需要在共享变量上使用volatile
关键字
编辑:抱歉,我粘贴了错误的代码