【发布时间】:2014-11-05 18:41:04
【问题描述】:
我想要一个类来启动一个线程并提供暂停和继续这个线程的方法。我的第一种方法是使用标志,只要值为真,它就会循环睡眠方法。类似的东西:
public class Bot {
private Thread t ;
private boolean isPaused;
public Bot(){
t = new Thread(new Runnable(){
@Override
public void run() {
while (true) {
System.out.println("Hi");
while(isPaused){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
t.start();
}
public void pauseBot(){
isPaused = true;
}
public void continueBot(){
isPaused = false;
}
}
但由于线程仍在运行并浪费 CPU,我认为这不是一个好的解决方案。使用 wait() 和 notify() 会怎样。 我查看了有关该主题的各种教程,但不知何故我无法将它们应用于我的问题。
每次我尝试它时,要么得到 IllegalMonitorStateException,要么代码停止了我的整个应用程序,而不仅仅是我想停止的线程。
我的另一个问题是:如何防止线程在关键时刻暂停,例如
Runnable r = new Runnable(){
@Override
public void run() {
while(true){
task1();
task2();
//Thread mustn't be stopped from here....
task3();
task4();
task5();
task6();
task7();
//... to here
task8();
task9();
task10();
}
}
};
因为当 task3() .... task7() 处理在线程暂停时会过期的东西时,必须有一种方法让线程完成 task7() 直到它暂停。
我希望你能帮助我解决我的问题。 提前致谢, 弗洛尔
【问题讨论】:
标签: java multithreading wait synchronized notify