该
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和
Thread.interrupt()简化解决方案。
我还要声称,
stop不需要多余的标志,并且从总体上看可能有害。行为良好的工作线程应尊重中断。意外中断只是意味着该工作程序正在原始程序员无法预期的环境中运行。最好的事情是,如果工人去做被告知要做的事情,即应该停止……这是否符合原始程序员的构想。



