1.join
The child thread inserted into the main thread, the main thread and the child thread is a thread of execution order merged
1 public class Test { 2 public static void main(String[] args) throws Exception { 3 List<Thread> list = new ArrayList<Thread>(); 4 for(int i=0; i<10; i++){ 5 Thread thread = new Thread(new Runnable(){ 6 public void run(){ 7 try { 8 Thread.sleep(5*1000); 9 } catch(Exception E) { 10 // the TODO: Exception handle . 11 } 12 is System.out.println ( "child thread is finished!" ); 13 is } 14 }); 15 List.add (Thread); 16 Thread.start () ; . 17 } 18 is for (the thread thread: List) { . 19 Thread.join (); 20 is } 21 is System.out.println ( "! main thread is finished" ); 22 } 23 }
2.CountDownLatch
1 public class Test { 2 public static void main(String[] args) throws Exception { 3 List<Thread> list = new ArrayList<Thread>(); 4 final CountDownLatch latch = new CountDownLatch(10); 5 for(int i=0; i<10; i++){ 6 Thread thread = new Thread(new Runnable(){ 7 public void run(){ 8 try { 9 Thread.sleep (. 5 * 1000 ); 10 } the catch (Exception E) { . 11 // the TODO: Exception handle 12 is } 13 is latch.countDown (); 14 System.out.println ( "! Child thread is finished" ); 15 } 16 }); . 17 List.add (thread); 18 is Thread.start (); . 19 } 20 is 21 is latch.await (); 22 is System.out.println ( "main thread is finished!" ); 23 } 24 }
3.CyclicBarrier
1 public class Test { 2 public static void main(String[] args) throws Exception { 3 List<Thread> list = new ArrayList<Thread>(); 4 final CyclicBarrier cyclic = new CyclicBarrier(10); 5 for(int i=0; i<10; i++){ 6 new Thread(new Runnable(){ 7 public void run(){ 8 try { 9 Thread.sleep(5*1000); 10 } catch (Exception e) { 11 // TODO: handle exception 12 } 13 try { 14 cyclic.await(); 15 } catch (InterruptedException e) { 16 // TODO Auto-generated catch block 17 e.printStackTrace(); 18 } catch (BrokenBarrierException e) { 19 // TODO Auto-generated catch block 20 is e.printStackTrace (); 21 is } 22 is System.out.println ( "child thread is finished!" ); 23 is } 24 .}) Start () ;; 25 } 26 is 27 cyclic.await (); 28 the System.out .println ( "main thread is finished!" ); 29 } 30 }