[英]ArrayBlockingQueue - How to “interrupt” a thread that is wating on .take() method
我在代码中使用ArrayBlockingQueue
。 客户将等待,直到某个元素可用:
myBlockingQueue.take();
万一队列中没有任何元素并且take()
无限期地等待某个元素变得可用,我该如何“关闭”我的服务? 此方法引发InterruptedException
。 我的问题是,如何才能“引发”一个中断异常,以便take()
退出? (我也对notify()
怀疑,但似乎我对此没有帮助。)
我知道我可以插入特殊的“ EOF / QUIT”标记元素,但这真的是唯一的解决方案吗?
UPDATE (关于注释,它指向具有两个解决方案的另一个问题):
上面提到的一个使用“中毒药丸对象”,第二个是Thread.interrupt()
:
该myBlockingQueue.take()
不使用的Thread
(扩展Thread),而是实现Runnable
。 似乎Runnable不提供.interrupt()
方法?
如何中断Runnable
?
您可以像这样实现Runnable。 (假定您在尝试中断它之前已经启动了Runnable)
class MyRunnable implements Runnable {
private Thread thisThread;
public void run() {
thisThread = Thread.currentThread();
try {
// do some work
} catch(Throwable t) {
t.printStackTrace(); // or log the error.
}
}
public void interrupt() {
thisThread.interrupt();
}
}
直接的方法是保留用于运行可运行线程并在关闭时中断它的线程的引用。
或者,您可以使用线程池来组织服务的线程。 然后,线程池负责跟踪和管理线程,包括在关闭线程时将其中断。
还有另一种(不建议使用的但不推荐的方法)方式是枚举JVM中所有正在运行的线程(使用ThreadGroup的方法),并尝试猜测哪个线程运行了您的可运行线程(例如,通过分析每个线程的堆栈)。
找到了解决方案:
可以按照问题“毒物”中的描述使用
要么
使用this.interrupt()
中断线程eitehr,或者如果它是可运行的,则使用Thread.currentThread().interrupt();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.