Java7新特性(四)并发 3 CountDownLatch计数器对象

本文主要根据《Java程序员修炼之道》整理的代码笔记片段

示例代码(用于一半线程初始化后,才执行后续代码)

public class ProcessingThread extends Thread {
	private final String ident;
	private final CountDownLatch latch;
	private static int MAX_THREADS = 17;
	
	public ProcessingThread(String ident_, CountDownLatch cdl_) {
		ident = ident_;
		latch = cdl_;
	}

	public String getIdentifier() {
		return ident;
	}

	public void initialize() {
		latch.countDown();
	}

	public void run() {
		try {
			TimeUnit.SECONDS.sleep(1);//Java 5 写法
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		initialize();
		 System.out.println(ident + "|"+latch.getCount());
	}
	
	public static void main(String[] a) {
		final int quorum = 1 + (int) (MAX_THREADS / 2);
		final CountDownLatch cdl = new CountDownLatch(quorum);
		final Set<ProcessingThread> nodes = new HashSet<>();
	    
	    try {
	    	for (int i = 0; i < MAX_THREADS; i++) {
	    		 ProcessingThread local = new ProcessingThread(
	    		            "localhost:" + (9000 + i), cdl);
	    		 nodes.add(local);
	    		 local.start();
	    		 //System.out.println("localhost:" + (9000 + i) + "|"+cdl.getCount());
			}
			cdl.await();//阻塞
			System.out.println(cdl.getCount());
		} catch (InterruptedException e) {
			
		}finally{
			
		}
	}
}
结果:

localhost:9003|7
localhost:9010|5
localhost:9015|4
localhost:9012|6
localhost:9007|2
localhost:9014|7
localhost:9008|1
localhost:9011|3
localhost:9000|0
0
localhost:9002|0
localhost:9004|0
localhost:9006|0
localhost:9013|0
localhost:9001|0
localhost:9005|0
localhost:9009|0
localhost:9016|0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值