LinkedBlockingQueue 抛出 InterruptedException
我有这段代码。如果在等待添加到队列时被中断,LinkedBlockingQueue
只应抛出 Exception
。但这个队列是无限的,所以它应该尽快添加。为什么我的关闭方法会抛出 InterruptedException?
private final LinkedBlockingQueue<Message> messages= new LinkedBlockingQueue<Message>();
public void run(){
LinkedList<Message> messages = new LinkedList<Message>();
while (true){
try{
messages.clear();
messages.add(this.messages.take());
this.messages.drainTo(messages);
for (Message message:messages){
if(message.isPoison())return;
doSomething(message);
}
}catch(Exception e){
getLogger().addException(e);
}
}
}
protected void add(Message m){
try {
messages.put(m);
}catch (InterruptedException e) {
getLogger().addException(e);
addRollback(e);
}
}
public void shutdown(){
try{
messages.put(MessageFactory.getPoison());
}catch(InterruptedException e){
//here an exception is thrown. Why?
}
}
I have this piece of code. A LinkedBlockingQueue
should only throw an Exception
if interrupted while waiting to add to the queue. But this queue is unbounded so it should add asap. Why does my shutdown methode throw an InterruptedException
?
private final LinkedBlockingQueue<Message> messages= new LinkedBlockingQueue<Message>();
public void run(){
LinkedList<Message> messages = new LinkedList<Message>();
while (true){
try{
messages.clear();
messages.add(this.messages.take());
this.messages.drainTo(messages);
for (Message message:messages){
if(message.isPoison())return;
doSomething(message);
}
}catch(Exception e){
getLogger().addException(e);
}
}
}
protected void add(Message m){
try {
messages.put(m);
}catch (InterruptedException e) {
getLogger().addException(e);
addRollback(e);
}
}
public void shutdown(){
try{
messages.put(MessageFactory.getPoison());
}catch(InterruptedException e){
//here an exception is thrown. Why?
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果线程处于中断状态,即Thread.interrupted() == true,则调用将抛出
InterruptionException
。这并不一定意味着线程在您放置时被中断,它可能已经处于进入之前的状态。If the thread is in a state of interruption, that is Thread.interrupted() == true, then the call will throw an
InterruptionException
. It doesn't necessarily mean that the thread was interrupted while you wereput
ting, it could have already been in the state before entering.