[英]wake up waiting threads
该课程与执行者一起工作。 事实是,在某个时候我想关闭它,但是即使我将terminateRequested更改为“ true”,它也不会帮助那些在“ takeTask”中等待的线程,因为此时的矢量任务始终为空。 我需要它们以某种方式到达run()中的“ e.shutDown()”行
public class RunnableStudent implements Runnable{
public void run() {
while(!terminateRequested){
this.takeTask();
this.giveSolution();
}
e.shutdown();
}
private synchronized void takeTask(){
while(tasks.isEmpty()){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
DoSomeWork();
}
public synchronized void shutDown(){
terminateRequested = true;
this.notifyAll();
}
您将需要跳出while tasks.isEmpty()){
循环,而跳出while(!terminateRequested){
循环
所以我建议你做的时候
} catch (InterruptedException e) {
e.printStackTrace();
}
您将其更改为
} catch (InterruptedException e) {
terminateRequested = true;
return;
}
由于看不到您的giveSolution
方法,因此无法告诉您必须更改它。
另外,您可以通过takeTask
方法中的InterruptedException
。
由于您使用的是执行程序服务,因此可以调用它的shutdownNow方法来主动关闭线程,而无需等待。
将Object.wait和Object.notify与java.util.concurrent气味组合在一起, 是否直接使用Object.wait和Object.notify产生代码气味?
您需要打破while(tasks.isEmpty())的循环,因此需要更改代码,如下所示:
public class RunnableStudent implements Runnable{
private Thread thread;
public void run() {
thread = Thread.currentThread();
while(!terminateRequested){
this.takeTask();
this.giveSolution();
}
e.shutdown();
}
private synchronized void takeTask(){
while(tasks.isEmpty()){
try {
this.wait();
} catch (InterruptedException e) {
break;
}
}
DoSomeWork();
}
public synchronized void shutDown(){
terminateRequested = true;
thread.interupt();
}
首先,如果您拥有三个不同的RunnableStudent实例(每个线程每个实例),并且假定任务和TerminateRequested是局部变量,则无需同步。因为线程之间没有共享的对象。
其次,如果您使用执行程序,则可以使用线程池,这种情况下您无需等待并通知自己,一旦工作完成,则池中的所有线程(在池初始化时配置了n个线程)将等待下一个请求(通过executors.submit / execute)。 而且,您可以根据自己的情况在任何给定点使用shutdown / shutdownNow。
最后回答您的问题,只需将while循环更改为taketask()中的if条件。 您所有的问题都会解决。 因为您的等待逻辑在run方法中的main while循环中仍然会很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.