【2013-12-16】《Java编程思想》读书笔记:CountDownLatch

【2013-12-16】《Java编程思想》读书笔记:CountDownLatch

[历史归档]本文原发布于 cstriker1407.info 个人博客,内容为历史存档,仅供参考。
发布时间:2013-12-16| 标题:《Java编程思想》读书笔记:CountDownLatch分类:编程 / java / think_in_java |标签:java·think in java·多线程·CountDownLatch


《Java编程思想》读书笔记:CountDownLatch

最近在整理 Java 的多线程相关的技术,这里备份下关于【 CountDownLatch 】代码。

github:

【 https://github.com/cstriker1407/think_in_java 】

CountDownLatch主要用来完成一个计数器锁的业务,即计数完成前线程会等待。这里备份下代码:

publicclassCountDownLatchTest{publicstaticvoidtest(){CountDownLatchstartSignal=newCountDownLatch(1);CountDownLatchdoneSignal=newCountDownLatch(3);for(inti=0;i<3;++i){newThread(newWorker(startSignal,doneSignal)).start();}try{Thread.sleep(1000);}catch(InterruptedExceptione1){e1.printStackTrace();}System.out.println("the runnables are inited");System.out.println("the runnables are free to start");startSignal.countDown();try{doneSignal.await();}catch(InterruptedExceptione){e.printStackTrace();}}}classWorkerimplementsRunnable{privatestaticintcount=0;privateintidx=0;privatefinalCountDownLatchstartSignal;privatefinalCountDownLatchdoneSignal;Worker(CountDownLatchstartSignal,CountDownLatchdoneSignal){this.startSignal=startSignal;this.doneSignal=doneSignal;idx=count++;}publicvoidrun(){try{System.out.println("the runnable is begin to init:"+idx);startSignal.await();System.out.println("the runnable is begin to start:"+idx);Thread.sleep(2000);doneSignal.countDown();System.out.println("the runnable is finish:"+idx);}catch(InterruptedExceptionex){}// return;}}

日志显示:

the runnable is begin to init:0 the runnable is begin to init:2 the runnable is begin to init:1 the runnables are inited the runnables are free to start the runnable is begin to start:2 the runnable is begin to start:1 the runnable is begin to start:0 the runnable is finish:1 the runnable is finish:0 the runnable is finish:2