我ArrayBlockingQueue在我的代码中使用了一个.客户端将等待元素可用:
myBlockingQueue.take();
Run Code Online (Sandbox Code Playgroud)
如果队列中没有元素并且take()无限期地等待元素变为可用,我如何"关闭"我的服务?这个方法抛出一个InterruptedException.我的问题是,我怎样才能"唤起"一个中断的异常以便take()退出?(我也考虑过notify(),但似乎我在这里没有帮助..)
我知道我可以插入一个特殊的"EOF/QUIT"标记元素,但这真的是唯一的解决方案吗?
更新(关于评论,指出另一个问题有两个解决方案):
上面提到的一个使用"中毒丸对象",第二个是Thread.interrupt():
在myBlockingQueue.take()使用NOT在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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2131 次 |
| 最近记录: |