gpt4 book ai didi

java - LinkedBlockingQueue 抛出 InterruptedException

转载 作者:行者123 更新时间:2023-12-02 08:20:11 26 4
gpt4 key购买 nike

我有这段代码。如果在等待添加到队列时被中断,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?
}

}

最佳答案

如果线程处于中断状态,即Thread.interrupted() == true,则调用将抛出InterruptionException。这并不一定意味着线程在您put时被中断,它可能已经处于进入之前的状态。

关于java - LinkedBlockingQueue 抛出 InterruptedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5635923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com