Java并发-类库新组件 - CountDownLatch 理解

来源:互联网 发布:道路算量用什么软件 编辑:程序博客网 时间:2024/06/01 21:08
</pre><pre name="code" class="java">
直接附加上练习代码
package com.xyw.concurrent.blog;import java.util.concurrent.*;import java.util.*;/* * CountDownLatch 是进行同步一个或者多个任务,强制他们等待由其他任务执行的一组操作完成。 * 其有个初始的计数值,wait 的值都将被阻塞,直到计数值达到零的情况。 并且CountDownLatch 只能进行一次触发。计数器不能被重置。 * 如果被重置,请看下一期的讲解的情况。 */class TaskPortion implements Runnable{private  static int counter = 0;private final int id = counter++; // 进行设置自增的ID 的选项private static Random rand = new Random(47);private final CountDownLatch latch;TaskPortion(CountDownLatch latch){this.latch = latch;}public void run(){try{doWork();latch.countDown();}catch(InterruptedException ex){}}public void doWork() throws InterruptedException{TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000));System.out.println(this + "completed!");}public String toString(){return String.format("%1$-3d",id);}}// 这是个进行分开执行的任务, performs some portion of a taskclass WaitingTask implements Runnable{private static int counter = 0;private final int id = counter++;private final CountDownLatch latch;WaitingTask(CountDownLatch latch){this.latch = latch;}public void run(){try{latch.await(); // 进行等待,知道 计数值为 零的时候,发生其中的停止的情况System.out.println("Latch barrier passed for " + this);//System.out.println(latch.getCount()); // 这个是用来进行监视,是不是其中运行的关键值得情况。}catch(InterruptedException e){System.out.println(this + " interrupted");}}public String toString(){return String.format("WaitingTask %1$-3d", id);}}public class CountDownLatchDemo {static final int SIZE = 10; // 你可以进行改变 SIZE 的值来进行了解 CountDownLatch 类的原理的情况public static void main(String[] args) throws Exception{ExecutorService exec = Executors.newCachedThreadPool();CountDownLatch latch = new CountDownLatch(SIZE);for(int i = 0; i< 100; i++){exec.execute(new WaitingTask(latch));}for(int i = 0; i < SIZE; i++){exec.execute(new TaskPortion(latch)); // 这些都是线程的进行的工作,并且只有// 其中的情况,等于一百的时候, WaitingTask 才进行运行,注意其中线程的先后的关系不是唯一确定的情况。}System.out.println("Launched all tasks");exec.shutdown(); // 当所有任务结束时完成System.out.print(latch.getCount()+ "\n");}}
// 运行结果
<pre name="code" class="java">Launched all tasks107  completed!9  completed!5  completed!8  completed!1  completed!2  completed!6  completed!4  completed!0  completed!3  completed!Latch barrier passed for WaitingTask 6  Latch barrier passed for WaitingTask 2  Latch barrier passed for WaitingTask 9  Latch barrier passed for WaitingTask 0  Latch barrier passed for WaitingTask 4  Latch barrier passed for WaitingTask 5  Latch barrier passed for WaitingTask 8  Latch barrier passed for WaitingTask 3  Latch barrier passed for WaitingTask 7  Latch barrier passed for WaitingTask 1  




0 0