java - java中的暂停和恢复线程不起作用
问题描述
我想分别使用 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.
解决方案
问题是这些行:
while (suspend.isSuspend)
wait();
}
在你的counterThread
Runnable 中。
你在等待Runnable
,而不是在suspend
对象上
您需要同步suspend
并调用 wait() on suspend
:
synchronized (suspend) {
while (suspend.isSuspend)
suspend.wait();
}
}
此外,您的run
方法不需要同步。
推荐阅读
- java - 是否可以使用 kafka-console-producer 通过事务客户端发送消息?
- spring - 如何将自定义 OAuth2AuthorizationFailureHandler 添加到 DefaultOAuth2AuthorizedClientManager?
- wolfram-mathematica - 在 Mathics 中将列表或数组元素打印为下标
- r - esquisserUI 小部件因 Shiny 中 uiOutput 的自动缩放而错位
- angular - npm install 不会安装正确的包
- php - PHP Regex 获取自定义文档参数
- java - 在 Spring 中使用 RestTemplate 进行复杂的 Json 映射
- .net - VB.NET 在不同位置的 PictureBox 上绘制多个图像
- ios - 启动反应原生应用程序会出现工具链或 AppRegistry 错误
- python - 我想在不编辑代码的情况下将站点添加到我的 url 字符串