3

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?
4

3 に答える 3

7

を呼び出しているスレッドを中断する必要がありますqueue.put(...);put(...);呼び出しはwait()何らかの内部条件で実行されており、呼び出しているスレッドがput(...)中断された場合、wait(...)呼び出しはスローInterruptedExceptionされ、それはによって渡されますput(...);

// interrupt a thread which causes the put() to throw
thread.interrupt();

スレッドを取得するには、作成時に保存できます。

Thread workerThread = new Thread(myRunnable);
...
workerThread.interrupt();

または、Thread.currentThread()メソッド呼び出しを使用して、他の人が割り込みに使用できるようにどこかに保存することもできます。

public class MyRunnable implements Runnable {
     public Thread myThread;
     public void run() {
         myThread = Thread.currentThread();
         ...
     }
     public void interruptMe() {
         myThread.interrupt();
     }
}

最後に、がスローされるとスレッドの割り込みステータスがクリアされる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
}
于 2013-04-03T13:30:32.197 に答える