gpt4 book ai didi

java - 如何中断在 take() 上阻塞的 BlockingQueue?

转载 作者:IT老高 更新时间:2023-10-28 11:44:54 25 4
gpt4 key购买 nike

我有一个类,它从 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?
}

最佳答案

如果中断线程不是一种选择,另一种方法是在队列上放置一个“标记”或“命令”对象,MyObjHandler 将识别为这样并跳出循环。

关于java - 如何中断在 take() 上阻塞的 BlockingQueue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/812342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com