1 import java.util.concurrent.CountDownLatch; 2 import java.util.concurrent.ExecutorService; 3 import java.util.concurrent.Executors; 4 5 public class CountdownLatchTest1 { 6 7 public static void main(String[] args) { 8 ExecutorService service = Executors. newFixedThreadPool(3); 9 final CountDownLatch latch = new CountDownLatch(3); 10 for (int i = 0; i < 3; i++) { 11 Runnable runnable = new Runnable() { 12 13 @Override 14 public void run() { 15 try { 16 System. out.println("子線程" + Thread.currentThread().getName() + "開始執行"); 17 Thread. sleep((long) (Math. random() * 10000)); 18 System. out.println("子線程" + Thread.currentThread().getName() + "執行完成"); 19 latch.countDown(); // 當前線程調用此方法,則計數減一 20 } catch (InterruptedException e) { 21 e.printStackTrace(); 22 } 23 } 24 }; 25 service.execute(runnable); 26 } 27 28 try { 29 System. out.println("主線程" + Thread.currentThread().getName() + "等待子線程執行完成..." ); 30 latch.await(); // 阻塞當前線程,直到計時器的值爲0 31 System. out.println("主線程" + Thread.currentThread().getName() + "開始執行..."); 32 } catch (InterruptedException e) { 33 e.printStackTrace(); 34 } 35 } 36 }
1 import java.util.concurrent.CountDownLatch; 2 import java.util.concurrent.ExecutorService; 3 import java.util.concurrent.Executors; 4 5 public class CountdownLatchTest2 { 6 7 public static void main(String[] args) { 8 ExecutorService service = Executors. newCachedThreadPool(); 9 final CountDownLatch cdOrder = new CountDownLatch(1); 10 final CountDownLatch cdAnswer = new CountDownLatch(4); 11 for (int i = 0; i < 4; i++) { 12 Runnable runnable = new Runnable() { 13 public void run() { 14 try { 15 System. out.println("選手" + Thread.currentThread().getName() + "正等待裁判發佈口令"); 16 cdOrder.await(); 17 System. out.println("選手" + Thread.currentThread().getName() + "已接受裁判口令"); 18 Thread. sleep((long) (Math. random() * 10000)); 19 System. out.println("選手" + Thread.currentThread().getName() + "到達終點"); 20 cdAnswer.countDown(); 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } 24 } 25 }; 26 service.execute(runnable); 27 } 28 try { 29 Thread. sleep((long) (Math. random() * 10000)); 30 31 System. out.println("裁判" + Thread.currentThread ().getName() + "即將發佈口令" ); 32 cdOrder.countDown(); 33 System. out.println("裁判" + Thread.currentThread ().getName() + "已發送口令,正在等待全部選手到達終點" ); 34 cdAnswer.await(); 35 System. out.println("全部選手都到達終點" ); 36 System. out.println("裁判" + Thread.currentThread ().getName() + "彙總成績排名" ); 37 } catch (Exception e) { 38 e.printStackTrace(); 39 } 40 service.shutdown(); 41 42 } 43 }