我正在使用一个不断从队列中读取的线程。
类似于:
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()
已弃用,我可以实现一个使用 n 原子检查条件变量的 stopThisThread()
方法。
2 - 将死亡事件对象或类似对象发送到队列。当线程获取死亡事件时,它会退出。
我更喜欢第一种方法,但是,我不知道什么时候调用 stopThisThread()
方法,因为可能有东西在去队列的路上,停止信号可以先到达(不可取)。
有什么建议吗?
最佳答案
如果您需要在关机前完成队列中的所有工作,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.
}
}
要停止使用 run
方法实例化的线程 t
,只需调用 t.interrupt();
。
如果将上面的代码与其他答案进行比较,您会注意到使用 BlockingQueue
和 Thread.interrupt()
如何简化解决方案。
我还声称额外的 stop
标志是不必要的,而且从大的角度来看,它可能有害。一个行为良好的工作线程应该尊重中断。意外中断仅仅意味着 worker 正在原始程序员没有预料到的上下文中运行。最好的事情是,如果工作人员按照它被告知的去做......即它应该停止......这是否符合原始程序员的概念。
关于java - 在 Java 中停止循环线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2720689/