我有一个类,它从BlockingQueue
中获取对象,并通过在连续循环中调用take()
来处理它们。在某种程度上,我知道不会再有对象被添加到队列中。如何中断take()
方法,使其停止阻塞?
下面是处理对象的类:
public class MyObjHandler implements Runnable {
private final BlockingQueue<MyObj> queue;
public class MyObjHandler(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
try {
while (true) {
MyObj obj = queue.take();
// process obj here
// ...
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
下面是使用这个类处理对象的方法:
public void testHandler() {
BlockingQueue<MyObj> queue = new ArrayBlockingQueue<MyObj>(100);
MyObjectHandler handler = new MyObjectHandler(queue);
new Thread(handler).start();
// get objects for handler to process
for (Iterator<MyObj> i = getMyObjIterator(); i.hasNext(); ) {
queue.put(i.next());
}
// what code should go here to tell the handler
// to stop waiting for more objects?
}
发布于 2009-05-01 17:29:25
如果不能中断线程,另一种方法是在队列上放置一个“标记”或“命令”对象,该对象将被MyObjHandler识别并跳出循环。
发布于 2009-05-01 17:27:10
BlockingQueue<MyObj> queue = new ArrayBlockingQueue<MyObj>(100);
MyObjectHandler handler = new MyObjectHandler(queue);
Thread thread = new Thread(handler);
thread.start();
for (Iterator<MyObj> i = getMyObjIterator(); i.hasNext(); ) {
queue.put(i.next());
}
thread.interrupt();
但是,如果这样做,当队列中仍有等待处理的项时,线程可能会中断。您可能希望考虑使用poll
而不是take
,这将允许处理线程在等待一段时间没有新输入时超时并终止。
发布于 2009-05-01 17:28:00
中断线程:
thread.interrupt()
https://stackoverflow.com/questions/812342
复制相似问题