java同步器——3——笔记

来源:互联网 发布:软件安全测试报告模板 编辑:程序博客网 时间:2024/05/16 06:24
<pre name="code" class="java">CountDownLatch 实例
package com.module;import java.util.concurrent.CountDownLatch;/** * 用于描述20个开发人员对模块进行开发,全部开发完之后再进行测试 * @author lihuafeng * */public class ModuleThread implements Runnable{private CountDownLatch latch;/** * 模块名字 */private String name;/** * 开发花费时间 */private String time;public ModuleThread(CountDownLatch latch, String name, String time) {super();this.latch = latch;this.name = name;this.time = time;}@Overridepublic void run() {this.work();latch.countDown();}public void work(){System.out.println(Thread.currentThread().getName() + "->完成模块:" + name + "花费时间:" + time);}}
</pre><pre name="code" class="java"><pre name="code" class="java">package com.module;import java.util.concurrent.CountDownLatch;public class TestThread implements Runnable{private CountDownLatch latch;public TestThread(CountDownLatch latch) {super();this.latch = latch;}@Overridepublic void run() {try {latch.await();System.out.println("可以全面开始测试工作!");} catch (InterruptedException e) {e.printStackTrace();}}}


</pre><pre name="code" class="java"><pre name="code" class="java">package com.module;import java.util.Random;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class CountDownLatchDemo {public static void main(String[] args) {Random r = new Random();CountDownLatch latch = new CountDownLatch(20);ExecutorService service = Executors.newCachedThreadPool();service.execute(new TestThread(latch));for(int i = 0 ; i < 20 ; i ++){service.execute(new ModuleThread(latch, "模块"+i, r.nextInt(2000)+""));}service.shutdown();}}




运行结果:

pool-1-thread-2->完成模块:模块0花费时间:276
pool-1-thread-3->完成模块:模块1花费时间:1172
pool-1-thread-4->完成模块:模块2花费时间:977
pool-1-thread-2->完成模块:模块5花费时间:72
pool-1-thread-4->完成模块:模块6花费时间:678
pool-1-thread-3->完成模块:模块4花费时间:1144
pool-1-thread-5->完成模块:模块3花费时间:1177
pool-1-thread-5->完成模块:模块8花费时间:1945
pool-1-thread-3->完成模块:模块9花费时间:882
pool-1-thread-6->完成模块:模块7花费时间:134
pool-1-thread-2->完成模块:模块11花费时间:795
pool-1-thread-12->完成模块:模块19花费时间:1959
pool-1-thread-11->完成模块:模块18花费时间:1432
pool-1-thread-10->完成模块:模块17花费时间:1950
pool-1-thread-9->完成模块:模块16花费时间:928
pool-1-thread-8->完成模块:模块15花费时间:638
pool-1-thread-7->完成模块:模块12花费时间:1324
pool-1-thread-3->完成模块:模块13花费时间:1998
pool-1-thread-5->完成模块:模块14花费时间:1124
pool-1-thread-4->完成模块:模块10花费时间:220
可以全面开始测试工作!

0 0