在一个主线程中,要求有大量子线程执行完之后,主线程才执行完成?多种方式,考虑效率。
2020-04-20 08:53
417 查看
1、在主函数中使用join()方法。
t1.start(); t2.start(); t3.start(); t1.join();//不会导致t1和t2和t3的顺序执行 t2.join(); t3.join(); System.out.println("Main finished");
2、CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
public class WithLatch{ public static void main(String[] args){ CountDownLatch latch = new CountDownLatch(3); for(int i=0;i<3;i++){ new ChildThread(i,latch).start(); } try{ latch.await(); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println("Main finished"); } static calss ChildThread extends Thread{ private int id = -1; private CountDownLatch latch = null; public ChildThread(int id, CountDownLatch latch){ this.id = id; this.latch = latch; } public void run(){ try{ Thread.sleep(Math.abs(new Random().nextInt(5000))); System.out.println(String.format("Child Thread %d finished",id)); }catch(InterruptedExcepion e){ e.printStackTrace(); }finally{ latch.countDown(); } } } }
3、使用线程池
public class WithExecutor{ public static void main(String[] args) throws InterruptedExcepion{ ExecutorService pool = Executors.newFixedThreadPool(3); List<Callable<Void>> list = new ArrayList<Callable<Void>>(); for(int i=0;i<3;i++){ list.add(new ChildThread(i)); } try{ pool.invokeAll(list); }finally{ pool.shutdown(); } System.out.println("Main finished"); } static class ChildThread implements Callable<Void>{ private int id = -1; public ChildThread (int id){ this.id = id; } public Void call() throws Exception{ try{ Thread.sleep(Math.abs(new Random().nextInt(5000))); System.out.println(String.format("Child Thread %d finished",id)); }catch(InterruptedException e){ e.printStackTrace(); } return null; } } }
相关文章推荐
- 主线程在分支线程运行完成之后执行
- 执行主线程之后又执行了几个子线程,保证子线程执行完成在结束主线程
- 使用管道流和多线程完成以下任务要求: 一个线程对象t1 会从控制台中不停的读取信息,读到之后把数据交给管道输出流,把数据写到管道里面 ,另一个线程对象t2 不停的使用管道输入流从管道
- [c/c++] 一个进程有多个线程,用什么方法让主线程不退出更好,要求占用资源最少,效率最高
- 如何等待一个线程完成后才继续执行之后的操作
- 主线程等待所有子线程执行完成之后再继续往下执行的解决方案
- 算法、编码时间、执行效率,一个都不能少——写在参加Google编程挑战赛之后
- 一个主线程下有多个子线程任务,主线程必须在100秒内将子线程执行的集合结果进行处理返回
- 多个线程运行结束之后主线程再执行CountDownLatch
- 多线程执行时,如果一个逻辑需要等若干个线程执行完成后再执行,怎么实现?
- 主线程等待所有子线程完成后再执行
- .Net最简单的创建多线程主线程等待所有线程执行完成的例子
- 主线程等待几个子线程执行完成方案
- 两个线程A和B,任务都是打印当前时间,要求编码实现:线程A和B同时启动后,以先A后B的方式任务交叉执行10次。
- 主线程等待所有子线程完成后再执行
- 子线程返回前,使循环暂停但不使主线程卡死的办法,等待子线程有返回了之后,才执行主线程下一步代码的方法
- JAVA主线程等待所有子线程执行完成后主线程再执行
- 多种方法实现当jsp页面完全加载完成后执行一个js函数
- 多线程用同一个dao对象就会存在多个线程执行同一方法,为什么不用考虑线程安全问题
- 一个完整的操作UI线程的例子,用到了多种方式