您需要中断正在调用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();
}
}
最后,当你 catchInterruptedException
时立即重新中断线程是一个很好的模式,因为当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
}