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

📅 2026/7/29 14:59:17
【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(){CountDownLatchstartSignalnewCountDownLatch(1);CountDownLatchdoneSignalnewCountDownLatch(3);for(inti0;i3;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{privatestaticintcount0;privateintidx0;privatefinalCountDownLatchstartSignal;privatefinalCountDownLatchdoneSignal;Worker(CountDownLatchstartSignal,CountDownLatchdoneSignal){this.startSignalstartSignal;this.doneSignaldoneSignal;idxcount;}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