java线程和主线程 [英] java threads and main thread

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

问题描述

使主线程等到所有线程完成的最佳方法是什么?

what's the best way to make main thread to wait until all threads are finished?


for(int i=0;i<n;i++){
   Thread t=new Thread();
   t.start();

}

//wait for all threads to finish


推荐答案

创建一个列表并等待所有。

Create a list and wait for the all.

List<Thread> threads = new ArrayList<Thread>();
for(int i=0;i<n;i++){
    Thread t=new Thread();
    t.start();
    threads.add(t);
}

for(Thread t: threads) t.join();

然而,使用ExecutorService可以更好地处理线程池。

However using an ExecutorService can be a more elegant way to handle a pool of threads.

ExecutorService es = Executors.newCachedThreadPool();
for(int i=0;i<n;i++)
   es.submit(new Task(n));
es.shutdown();
es.awaitTermination(timeout, TimeUnit.SECONDS);

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

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