带线程的观察者模式 [英] Observer pattern with threads

查看:132
本文介绍了带线程的观察者模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行几个线程并在主方法结束时加入,所以我可以知道他们什么时候完成并处理一些信息。

I want to run several threads and join them at the end of my main method, so I can know when they have finished and process some info.

不想把我的线程放在一个数组中,并且一个接一个连接(),因为连接是一个阻塞方法,我留在主线程中等待一些仍在运行的线程,而其他线程可能已经完成,没有有一个可能的知识。

I don't want to put my threads in an array and do a join() one by one as join is a blocking method and I stay would waiting in the main thread for some threads still running, while other threads may have already finished, without having a possibility of knowing.

我已经考虑了为我的线程实现一个观察者模式的可能性:一个带有update()方法的接口,一个从线程扩展的抽象类(或实现runnable)与set和get方法为听众和一个类开始我的所有线程和等待他们完成。

I have thought on the possibility of implementing an observer pattern for my threads: An interface with a update() method, an abstract class extending from thread (or implementing runnable) with set and get methods for the listeners and a class starting all my threads and waiting them to finish.

如果我的理解是正确的,观察者将不阻塞一个线程的特定连接()。相反,它将等待某种方式,直到一个update()方法被一个线程调用来执行一个动作。在这种情况下,update()应该在线程完成之后调用。

If my understanding is right, an observer would not block in a specific join() for a thread. Instead it will wait somehow until an update() method is called by a thread to perform an action. In this case, the update() should be called right after the thread finishes.

我对如何实现这个没有任何意义。我已经尝试过类似的模型,但我不知道如何使用观察者/监听器来唤醒/阻止我的主线程。我使用这个旧帖子作为模板:如何知道其他线程已经完成?,但一旦线程调用update()方法,我找不到一种方法来唤醒我的主要方法。只有一个观察对象被实例化为所有线程。

I'm clueless on how to implement this. I've tried with similar models, but I don't know how to use the observer/listener to wake/block my main thread. I've used this old post as a template: How to know if other threads have finished? but I can't find a way to wake my main method once a thread calls the update() method. There will be only one observer object instantiated for all threads.

你能想到一种使用观察者模式等待所有线程完成的方法,而不用主屏蔽通过一个join()调用?任何其他解决这个问题的建议将不胜感激。感谢提前。

Could you think of a way to use an observer pattern to wait for all threads to finish without blocking main with one by one join() calls? Any other suggestion to solve this problem would be greatly appreciated. Thanks in advance.

推荐答案

我认为你不需要一个观察者模式。线程等待任何结果将不得不阻止,否则将完成或循环无穷大。您可以使用某种BlockingQueue - 生产者会将计算结果添加到阻塞队列(然后完成),而主线程只会在没有任何结果时收到这些结果。

I think you don't need an observer pattern. Thread waiting for any results will have to block, otherwise it will finish or loop in infinity. You can use some kind of BlockingQueue - producers will add result of computation to the blocking queue (then finish) and main thread will just receive these results blocking when there's not any result yet..

你的好消息,已经实现了:) CompletionService 执行器框架的很好的机制。尝试这样:

Good news for you, it's already implemented :) Great mechanism of CompletionService and Executors framework. Try this:

private static final int NTHREADS = 5;
private static final int NTASKS = 100;
private static final ExecutorService exec = Executors.newFixedThreadPool(NTHREADS);

public static void main(String[] args) throws InterruptedException {
    final CompletionService<Long> ecs = new ExecutorCompletionService<Long>(exec);
    for (final int i = 0; i < NTASKS ; ++i) {
        Callable<Long> task = new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                return i;
            }
        };
        ecs.submit(task);
    }
    for (int i = 0; i < NTASKS; ++i) {
        try {
            long l = ecs.take().get();
            System.out.print(l);
        } catch (ExecutionException e) {
            e.getCause().printStackTrace();
        }
    }
    exec.shutdownNow();
    exec.awaitTermination(50, TimeUnit.MILLISECONDS);
}

这篇关于带线程的观察者模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆