首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >阻塞队列和InterruptedException

阻塞队列和InterruptedException
EN

Stack Overflow用户
提问于 2012-06-13 23:49:33
回答 2查看 3.1K关注 0票数 1

我有一个A类,属性是LinkedBlockingQueue。在A的一个方法中,我调用了LinkedBlockingQueue.put()方法,因为我想在队列中插入一个项。但是,如果队列已满,我的线程将等待,直到空间可用,或者直到我的线程被中断。

问题是,即使我的线程被中断,我也希望项目在队列中。

有没有办法确保我的项目已被插入到队列中?

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-06-13 23:58:28

我看到的唯一方法是在循环中调用queue.put()。也许是这样吧

代码语言:javascript
复制
boolean added = false;

while ( !added){
    try{
        queue.put(value);
        added = true;
    }catch(InterruptedException ie){
        // do something if required

        // make sure to set the interrupted flag on the thread, since it was cleared
        // when the exception was thrown
        Thread.currentThread().interrupt();
    }
}

if(Thread.currentThread.isInterrupted()){
    // you were previously interrupted before, so try to exit gracefully
    return;
}
票数 2
EN

Stack Overflow用户

发布于 2012-06-13 23:54:18

您必须决定是否要等待队列是否已满。如果您设置了最大长度,您不能告诉它忽略最大长度。

如果队列太大,你可以做的是减慢生产者的速度。如果您愿意,这将允许您“忽略”最大值。例如在中断时。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11018668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档