简体   繁体   English

Java 等待集合中新对象的线程

[英]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.

相关问题 Java在启动新线程之前会自动等待线程完成 - Java automatically waits for thread to finish before starting a new one Java线程在异步任务上永远等待 - Java Thread waits forever on Async Task Thread2 等待 Thread1 完成启动 问题? Java - Thread2 waits Thread1 to complete to start Problem? Java Android:如何创建一个等待服务器消息并更新UI的线程? - Android: How to make a thread which waits for server messages and updates the UI? Java多线程:执行对象方法的线程是否取决于创建对象方法的线程? - Java Multithreading: Does the thread on which an objects method is executed depend on the thread on the thread in which it is created? 为什么在Java的新Collection库中牺牲了线程安全性? - Why was thread safety sacrificed in new Collection library in Java? 在Java中创建等待线程的main()循环的黄金标准是什么? - What is the gold standard for creating a main() loop that waits for a Thread in Java java错误:mainthread等待直到执行第二个线程 - java error: mainthread waits until second thread is executed 如何在Java中使线程等待1ms? - How can I make thread waits for 1ms in Java? Java:线程在对象上等待时是否释放所有监视器? - Java: Are all monitors released when thread waits on an object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM