[英]What is the correct way to dispose of a producer thread after the consumer thread gets notified of a synchronized change and falls out?
我的理解是,在向消费者通知同步变量更改后,如果消费者Thread
掉线并退出,则没有任何事情阻止生产者继续前进。 处理生产者线程的正确方法是什么? 有什么阻止从消费者的run()
方法调用Thread.interrupt()
的功能吗?
我正在尝试执行以下操作:
//in consumer
public void run() {
synchronized( checkSolution) {
while (!checkSolution.getIsSolutionValid) {
try{
checkSolution.wait()
} catch( InterruptedException ignore) {}
}
//valid soln received
System.out.println("reference");
checkSolution.interrupt();
doAmazingWorkWithSolution();
}
//MARK
}
//in producer (checkSolution)
public synchronized boolean getIsSolutionValid() { return isSolutionValid; }
public void run() {
while(true) {
try{
synchronized( this) {
if( fSolution.size() != correctSize) {
isSolutionValid = false;
Thread.sleep(500);
} else {
System.out.println(" Solution is correct size.");
isSolutionValid = true;
notifyAll();
}
}
} catch(InterruptedException ie) {
//Thread.currentThread().interrupt();
return;
}
}
}
现在,这是我注意到的,但我真的不明白:
在任何成功的中断下,生产者的中断标志都会被置位,但是在最终关闭之前,它会多次执行else
块中的代码。 如何避免在notify
过程中对if / else语句进行垃圾邮件处理?
如果我将checkSolution.interrupt()和“ amazing work”方法调用移到标记为//MARK
的行,则它的中断速度明显慢一些,执行了惊人的工作调用,但奇怪的是从不打印`println(“ reference”);
如果我从InterruptedException
删除了return语句,它会接收到中断并在Exception
块中终止一步,但对else语句进行垃圾邮件处理达数十亿次,然后再次将其插入Thread.sleep
块,就像被中断的标志一样已重置。
Thread.currentThread().interrupt();
生产者的InterruptException
中的代码是我在其他人的代码中看到的,但是无论是否包含它,它在这里似乎都没有做任何事情。
这些是我感到困惑的小事情。 主要的问题是,在消费者获得所需的东西之后,如何尽可能有效地关闭生产者,使其尽可能靠近消费者线程。
我认为您的工作水平太低。 如果只有一个生产者和使用者,则可以使用java.util.concurrent.SynchronousQueue
阻塞使用者,直到生产者完成工作为止。
出于Thread.currentThread().interrupt()
的目的,请参阅http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html 。 这样做是个坏主意
catch( InterruptedException ignore) {}
在一个while
循环中。 链接文章中的更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.