我正在使用一个不断从队列中读取的线程.
就像是:
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()方法,因为它可能在队列的路上,并且停止信号可以首先到达(不可取).
有什么建议?