如何中断BlockingQueue?

ift*_*hem 3 java concurrency android interrupt blocking

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

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?
Run Code Online (Sandbox Code Playgroud)

Gra*_*ray 7

您需要中断正在调用的线程queue.put(...);.该put(...);呼叫正在做wait()一些内部条件的场合,在调用线程put(...)被中断,wait(...)调用将抛出InterruptedException这是由传递put(...);

// interrupt a thread which causes the put() to throw
thread.interrupt();
Run Code Online (Sandbox Code Playgroud)

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

Thread workerThread = new Thread(myRunnable);
...
workerThread.interrupt();
Run Code Online (Sandbox Code Playgroud)

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

public class MyRunnable implements Runnable {
     public Thread myThread;
     public void run() {
         myThread = Thread.currentThread();
         ...
     }
     public void interruptMe() {
         myThread.interrupt();
     }
}
Run Code Online (Sandbox Code Playgroud)

最后,当你发现InterruptedException立即重新中断线程时,这是一个很好的模式,因为当InterruptedException抛出线程时,线程上的中断状态被清除.

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
}
Run Code Online (Sandbox Code Playgroud)