LinkedBlockingQueue 抛出 InterruptedException

发布于 2024-11-01 07:01:23 字数 1111 浏览 1 评论 0原文

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

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

魔法唧唧 2024-11-08 07:01:23

如果线程处于中断状态,即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 were putting, it could have already been in the state before entering.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文