ArrayBlockingQueue - 如何“中断”一个正在wating on .take()方法的线程 [英] ArrayBlockingQueue - How to "interrupt" a thread that is wating on .take() method

查看:1373
本文介绍了ArrayBlockingQueue - 如何“中断”一个正在wating on .take()方法的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的代码中使用 ArrayBlockingQueue 。客户将等待一个元素可用:

I use an ArrayBlockingQueue in my code. Clients will wait until an element becomes available:

myBlockingQueue.take();

如果队列中没有元素,我如何关闭我的服务, c $ c> take()无限期地等待元素变得可用?此方法会抛出 InterruptedException 。我的问题是,我如何唤起一个被中断的异常,使 take()将退出? (我也理会 notify(),但似乎我不帮助这里..)

How can I "shutdown" my service in case no elements are present in the queue and the take() is waiting indefinitely for an element to become available? This method throws an InterruptedException. My question is, how can I "evoke" an Interrupted Exception so that take() will quit? (I also tought about notify(), but it seems I doesn't help here..)

知道我可以插入一个特殊的EOF / QUIT标记元素,但这是真的唯一的解决方案吗?

I know I could insert an special "EOF/QUIT" marker Element but is this really the only solution?

UPDATE 指向具有两个解决方案的另一个问题):

UPDATE (regarding the comment, that points to another question with two solutions):

一个使用中毒丸对象提到的,第二个是 Thread.interrupt :

one mentioned above using a "Poisoning Pill Object" and the second one is Thread.interrupt():

使用 myBlockingQueue.take() strong>在 Thread (扩展Thread),而是实现 Runnable 。似乎Runnable不提供 .interrupt()方法?

The myBlockingQueue.take() is used NOT in a Thread (extending Thread) but rather implements Runnable. It seems a Runnable does not provide the .interrupt() method?

如何中断 Runnable

推荐答案

你可以这样实现Runnable。 (假设您在启动Runnable之前尝试中断它)

You can implement the Runnable like this. (It assumes you have started the Runnable before you attempt to interrupt it)

class MyRunnable implements Runnable {
    private Thread thisThread;
    public void run() {
       thisThread = Thread.currentThread();
       try {
          // do some work
       } catch(Throwable t) {
          t.printStackTrace(); // or log the error.
       } 
    }
    public void interrupt() {
       thisThread.interrupt();
    }
}

这篇关于ArrayBlockingQueue - 如何“中断”一个正在wating on .take()方法的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆