在一个主线程中,要求有大量子线程执行完之后,主线程才执行完成?多种方式,考虑效率。
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 ;