を呼び出しているスレッドを中断する必要があります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
}