我正在使用一个不断从队列中读取数据的线程。
就像是:
public void run() {
Object obj;
while(true) {
synchronized(objectsQueue) {
if(objectesQueue.isEmpty()) {
try {
objectesQueue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
obj = objectesQueue.poll();
}
}
// Do something with the Object obj
}
}
停止该线程的最佳方法是什么?
我看到两个选择:
1 - 自从Thread.stop()
已弃用,我可以实施stopThisThread()
使用 n 个原子检查条件变量的方法。
2 - 将死亡事件对象或类似的对象发送到队列。当线程获取死亡事件时,它退出。
我更喜欢第一种方式,但是,我不知道什么时候打电话stopThisThread()
方法,因为某些东西可能正在进入队列,并且停止信号可能首先到达(不合需要)。
有什么建议么?
The DeathEvent
(或者通常称为“毒丸”)如果您需要在关闭之前完成队列中的所有工作,那么方法很有效。问题是这可能需要很长时间。
如果你想尽快停止,我建议你这样做
BlockingQueue<O> queue = ...
...
public void run() {
try {
// The following test is necessary to get fast interrupts. If
// it is replaced with 'true', the queue will be drained before
// the interrupt is noticed. (Thanks Tim)
while (!Thread.interrupted()) {
O obj = queue.take();
doSomething(obj);
}
} catch (InterruptedException ex) {
// We are done.
}
}
停止线程t
用那个实例化的run
方法,只需调用t.interrupt();
.
如果您将上面的代码与其他答案进行比较,您会注意到如何使用BlockingQueue
and Thread.interrupt()
简化了解决方案。
我还想说额外的stop
flag 是不必要的,而且从大局来看,可能有害。行为良好的工作线程应该尊重中断。意外中断仅仅意味着工作线程正在原始程序员没有预料到的上下文中运行。最好的事情是,如果工作人员按照指示去做……即它应该停止……无论这是否符合原始程序员的构想。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)