首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何中断BlockingQueue?

如何中断BlockingQueue?
EN

Stack Overflow用户
提问于 2013-04-03 21:26:01
回答 3查看 4.3K关注 0票数 3

BlockingQueue.put可以抛出InterruptedException。如何通过抛出此异常来导致队列中断?

代码语言:javascript
复制
ArrayBlockingQueue<Param> queue = new ArrayBlockingQueue<Param>(NUMBER_OF_MEMBERS);
...
try {
    queue.put(param);
} catch (InterruptedException e) {
    Log.w(TAG, "put Interrupted", e);
}
...
// how can I queue.notify?
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-04-03 21:30:32

您需要中断正在调用queue.put(...);的线程。put(...);调用在某些内部条件下执行wait(),如果调用put(...)的线程中断,wait(...)调用将抛出由put(...);传递的InterruptedException

代码语言:javascript
复制
// interrupt a thread which causes the put() to throw
thread.interrupt();

要获取线程,您可以在创建线程时将其存储:

代码语言:javascript
复制
Thread workerThread = new Thread(myRunnable);
...
workerThread.interrupt();

或者,您可以使用Thread.currentThread()方法调用并将其存储在某个位置,以供其他人用于中断。

代码语言:javascript
复制
public class MyRunnable implements Runnable {
     public Thread myThread;
     public void run() {
         myThread = Thread.currentThread();
         ...
     }
     public void interruptMe() {
         myThread.interrupt();
     }
}

最后,当您捕获InterruptedException以立即重新中断线程时,这是一个很好的模式,因为当抛出InterruptedException时,线程上的中断状态将被清除。

代码语言:javascript
复制
try {
    queue.put(param);
} catch (InterruptedException e) {
    // immediately re-interrupt the thread
    Thread.currentThread().interrupt();
    Log.w(TAG, "put Interrupted", e);
    // maybe we should stop the thread here
}
票数 7
EN

Stack Overflow用户

发布于 2013-04-03 21:31:06

在添加param之前,调用put将等待空闲的插槽,流程可以继续。

如果您捕获在调用put时正在运行的线程(即,在调用put之前调用Thread t1 = Thread.currentThread() ),然后在另一个线程中对此调用interrupt (同时t1被阻塞)。

This example有一些类似的东西,它负责在给定的超时后调用中断。

票数 0
EN

Stack Overflow用户

发布于 2013-04-03 21:37:58

您需要具有对使用queue.put()运行代码的线程的引用,如本测试中所示

代码语言:javascript
复制
    Thread t = new Thread() {
        public void run() {
            BlockingQueue queue = new ArrayBlockingQueue(1);
            try {
                queue.put(new Object());
                queue.put(new Object());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
    };
    t.start();
    Thread.sleep(100);
    t.interrupt();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15788633

复制
相关文章

相似问题

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