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?发布于 2013-04-03 21:30:32
您需要中断正在调用queue.put(...);的线程。put(...);调用在某些内部条件下执行wait(),如果调用put(...)的线程中断,wait(...)调用将抛出由put(...);传递的InterruptedException
// 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-03 21:31:06
在添加param之前,调用put将等待空闲的插槽,流程可以继续。
如果您捕获在调用put时正在运行的线程(即,在调用put之前调用Thread t1 = Thread.currentThread() ),然后在另一个线程中对此调用interrupt (同时t1被阻塞)。
This example有一些类似的东西,它负责在给定的超时后调用中断。
发布于 2013-04-03 21:37:58
您需要具有对使用queue.put()运行代码的线程的引用,如本测试中所示
Thread t = new Thread() {
public void run() {
BlockingQueue queue = new ArrayBlockingQueue(1);
try {
queue.put(new Object());
queue.put(new Object());
} catch (InterruptedException e) {
e.printStackTrace();
}
};
};
t.start();
Thread.sleep(100);
t.interrupt();https://stackoverflow.com/questions/15788633
复制相似问题