java多執行緒協作CountDownLatch
阿新 • • 發佈:2018-12-12
CountDownLatch 是current 包下的常用的同步多執行緒行為的類, 構造中需要輸入一個計數值, 當這個值不為零時, 執行 await() 的執行緒會阻塞, 執行緒每次執行 countDown() 方法都會是計數值減一;
已多人賽跑為例, 建立多執行緒模型, 演示CountDownLatch 的功能
package _CountDownLatch; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchDemo { public static void main(String[] args) { //所有執行緒阻塞,然後統一開始 CountDownLatch begin = new CountDownLatch(1); //主執行緒阻塞,直到所有分執行緒執行完畢 CountDownLatch end = new CountDownLatch(5); for(int i = 0; i < 5; i++){ ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); newCachedThreadPool.execute(new Runnable() { @Override public void run() { try { begin.await(); System.out.println(Thread.currentThread().getName() + " 起跑 " + System.currentTimeMillis()); Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + " 到達終點 " + System.currentTimeMillis()); end.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } try { System.out.println("比賽開始"); Thread.sleep(1000); begin.countDown(); end.await(); System.out.println("停止比賽"); } catch (InterruptedException e) { e.printStackTrace(); } } }