在一個主線程中,要求有大量子線程執行完之后,主線程才執行完成?多種方式,考慮效率。


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; } } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM