java同步器——3——笔记

<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;
	}

	@Override
	public 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;
	}

	@Override
	public 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值