读书人

JDK-CountDownLatch-范例、源码和模拟

发布时间: 2013-09-15 19:58:13 作者: rapoo

JDK-CountDownLatch-实例、源码和模拟实现
ConceptionA synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
根据CountDownLatch的document,就是说CountDownLatch作为一个同步的助手,可以阻塞一个线程,等待另一个线程结束了再执行。
所以CountDownLatch的作用在于:通过阻塞来协调线程间的执行顺序。
CountDownLatch最重要的方法为await()和countDown()。首先,初始化指定一个count,每次countDown()都会count--,而await()就是阻塞调用它的方法,直到count==0。
所以可以把CountDownLatch看成同步的计数器,什么时候倒数到0就执行,否则阻塞。

Demo我们首先做一个CountDownLatch的demo,看看它是怎么一个阻塞。
count初始化为2,所以count.await()会阻塞主线程,直到两个processor都countDown(),即count==0的时候才会执行,打印出"Processors has been done."


public class CountDownLatchSimulator {private AtomicInteger count;public CountDownLatchSimulator(int count) {this.count = new AtomicInteger(count);}public void await() throws InterruptedException {while (this.count.get() != 0) {//Thread.currentThread().sleep(100);}}public void countDown() {this.count.getAndDecrement();}public static void main(String[] args) throws InterruptedException {CountDownLatchSimulator begin = new CountDownLatchSimulator(1);CountDownLatchSimulator end = new CountDownLatchSimulator(3);ExecutorService exc = Executors.newCachedThreadPool();System.out.println("Runners are comming.");exc.submit(new CountProcessor2(begin, end, "Runner_1", 1000));exc.submit(new CountProcessor2(begin, end, "Runner_2", 2000));exc.submit(new CountProcessor2(begin, end, "Runner_3", 3000));System.out.println("Ready.");Thread.currentThread().sleep(2000);System.out.println("Go.");begin.countDown();end.await();System.out.println("All runners Finish the match.");exc.shutdown();}}class CountProcessor2 extends Thread {private CountDownLatchSimulator beginCount;private CountDownLatchSimulator endCount;private String name;private int runningTime;public CountProcessor2(CountDownLatchSimulator beginCount, CountDownLatchSimulator endCount, String name, int runningTime) {this.beginCount = beginCount;this.endCount = endCount;this.name = name;this.runningTime = runningTime;}@Overridepublic void run() {try {this.beginCount.await();System.out.println(this.name + " start.");Thread.currentThread().sleep(this.runningTime);System.out.println(this.name + " breast the tape.");this.endCount.countDown();} catch (InterruptedException e) {e.printStackTrace();}}}

读书人网 >编程

热点推荐