標籤:thread 線程 java
package org.rui.thread.newc;import java.util.Random;import java.util.concurrent.CountDownLatch;import java.util.concurrent.Executor;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;/** * Latch 鎖存器 * 新類庫中的構件 countDownLatch * * @author lenovo * */class TaskPortion implements Runnable {private static int counter = 0;private final int id = counter++;private static Random rand = new Random(47);private final CountDownLatch latch;public TaskPortion(CountDownLatch latch) {this.latch = latch;}@Overridepublic void run() {try {doWork();latch.countDown();} catch (InterruptedException e) {// acceptable way to exit}}// 處理業務代碼public void doWork() throws InterruptedException {TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000));System.out.println(this + " 完成");}public String toString() {return String.format("%1$-3d", id);}}// waits on the countDownLatchclass WaitingTask implements Runnable {private static int counter = 0;// 計數private final int id = counter++;private static Random rand = new Random(47);private final CountDownLatch latch;WaitingTask(CountDownLatch latch) {this.latch = latch;}@Overridepublic void run() {try {// 調用countDown()的任務在產生調用時並沒有被阻塞,只有對await的調用會被阻塞,直至計數值到達0// 等待問題被解決的任務在這個鎖存器上調用await(),將它們自已攔住,直至鎖存器計數結束latch.await();System.out.println("latch 障礙被認為 " + this);} catch (InterruptedException e) {System.out.println(this + " interrupted");}}public String toString() {return String.format("waitingTask %1$-3d", id);}}/** * TaskPortio將隨機地休眠一段時間,以類比這部分工作的完成,而WaitingTask表示系統中等待的部分,它要等待到問題的初始部分成完為止, * 所有的任務都使用了在main中定義同一個單一的counDownLacth * * @author lenovo * */public class CountDownLatchDemo {static final int SIZE = 100;public static void main(String[] args) throws InterruptedException {ExecutorService exec = Executors.newCachedThreadPool();CountDownLatch latch = new CountDownLatch(SIZE);// 都必須共用一個countDownLatch對象for (int i = 0; i < 10; i++) {exec.execute(new WaitingTask(latch));// 這個要等待 latch上面的為0時才會執行}for (int i = 0; i < SIZE; i++) {exec.execute(new TaskPortion(latch));}// latch.await();System.out.println("launched all tasks");exec.shutdown();// quit when all task complete}}/**output:launched all tasks43 完成95 完成99 完成36 完成94 完成11 完成....12 完成1 完成27 完成98 完成13 完成72 完成71 完成2 完成45 完成92 完成31 完成14 完成17 完成6 完成97 完成....80 完成....56 完成85 完成61 完成30 完成....3 完成93 完成81 完成78 完成73 完成44 完成82 完成49 完成64 完成83 完成16 完成latch 障礙被認為 waitingTask 2 latch 障礙被認為 waitingTask 0 latch 障礙被認為 waitingTask 4 latch 障礙被認為 waitingTask 1 latch 障礙被認為 waitingTask 5 latch 障礙被認為 waitingTask 3 latch 障礙被認為 waitingTask 7 latch 障礙被認為 waitingTask 6 latch 障礙被認為 waitingTask 9 latch 障礙被認為 waitingTask 8 */
java 線程 新類庫中的構件 countDownLatch 使用