在所有子线程完成执行之后如何运行主线程 [英] how to run the main thread after all child threads have completed there exceution

查看:334
本文介绍了在所有子线程完成执行之后如何运行主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,其中28个线程必须完成某些功能.我已经在匿名内部类(如:

I have a requirement in which 28 threads have to complete some functionality. I have created these threads as in anonymous inner classes like :

Thread t=new Thread(new Runnable(){public void run() 
                        {//code
                        }}
                                );

                        t.start();

现在,我希望所有这些线程完成工作后再开始执行.

Now I want that the further execution should start after all these threads have finished there work.

注意:我对join()方法感到困惑,因为它使我的线程按顺序运行.

Note : I am confused about join() method as it makes my threads run sequentially.

所以有人可以建议我一旦这些线程完成工作后如何运行主线程.

So can anyone suggest me how can I make main thread run once these threads are done with work.

推荐答案

注意:我对join()方法感到困惑,因为它会使我的线程按顺序运行.

Note : I am confused about join() method as it makes my threads run sequentially.

如果您有这样的代码,它将这样做:

It will do that if you have code like this:

for (Runnable runnable : runnables) {
    Thread t = new Thread(runnable);
    t.start();
    t.join();
}

但是,您可以启动要并行运行的所有线程,然后然后在所有线程上调用join.例如:

However, you can start all the threads you want to run in parallel, then call join on them all. For example:

List<Thread> threads = new ArrayList<>();
for (Runnable runnable : runnables) {
    Thread t = new Thread(runnable);
    t.start();
    threads.add(t);
}
// Now everything's running - join all the threads
for (Thread thread : threads) {
     thread.join();
}

// Now you can do whatever you need to after all the
// threads have finished.

当然,还有许多其他方法-直接启动线程可能不如使用更高级别的抽象在您的代码中那么合适;这取决于您要实现的目标.上面的代码应该可以正常工作-假设所有Runnable都可以并行运行,而不会通过同步彼此阻塞.

There are many other approaches, of course - starting threads directly may well not be as suitable in your code as using a higher level abstraction; it depends on what you're trying to achieve. The above should work fine though - assuming all the Runnables are able to run in parallel without blocking each other through synchronization.

这篇关于在所有子线程完成执行之后如何运行主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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