[英]Java Thread which waits for new objects in collection
I have one thread which should execute some action when new object is added to collection.当新的 object 添加到集合中时,我有一个线程应该执行一些操作。 This collection is modified by several Callables.
此集合由几个 Callables 修改。 Thread which waits for new elements should be easy stopped after some time by boolean flag 'stopped'.
等待新元素的线程应该在一段时间后通过 boolean 标志“停止”轻松停止。
What are the possible ways for implementing that?实现它的可能方法是什么? I didn't find good examples of implementing that.
我没有找到实现它的好例子。
Well, you could wrap your collection in a custom one and register a listener.好吧,您可以将您的集合包装在一个自定义集合中并注册一个侦听器。 Example with
LinkedBlockingQueue
: LinkedBlockingQueue
示例:
public class MyCollection<T> extends LinkedBlockingQueue<T> {
private final MyListener<T> listener;
public MyCollection(MyListener<T> listener) {
this.listener = listener;
}
@Override
public void put(T t) throws InterruptedException {
super.put(t);
listener.onPut(t);
}
}
public class MyListener<T> {
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
public void onPut(T t) {
executorService.submit(() -> doSomething(t));
}
public void stop() {
executorService.shutdown();
// optional call to awaitTermination() here..
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.