CountDownLatch简单实例介绍

废话不说直接上代码:

import java.util.concurrent.CountDownLatch;
public class hehed implements Runnable {
	private CountDownLatch controller;


	public hehed(int number) { // ???
		controller = new CountDownLatch(number);
	}


	public void arrive(String name) {
		System.out.println(name + " 名字");
		controller.countDown();
		System.out.println("------------" + controller.getCount());
	}


	@Override
	public void run() {
		System.out.println("第一步主程序跑:");
		try {
			controller.await();
			System.out.printf("全部开始");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}


class Participant implements Runnable {
	private hehed conference;
	private String name;


	public Participant(hehed conference, String name) {
		this.conference = conference;
		this.name = name;


	}


	@Override
	public void run() {
		System.out.println("第二个:-----");
		conference.arrive(name);
	}


}

测试类-----------------
public class TestTTTTTTT {

	public static void main(String[] args) {

			hehed hd=new hehed(9);
	        Thread threadConference = new Thread(hd); // 
	        threadConference.start();  
	        for(int i=0;i<10;i++){  
	            Participant p = new Participant(hd, "小明"+i);  
	            Thread t = new Thread(p);  
	            t.start();  
	        }  


	}

}

CountDownLatch有以下基本方法:

1)await(),阻塞等待,直到计数器清零

 

2)await(int timeout, TimeUnit unit),使线程阻塞,除非被中断或者超过等待的最大时间

如果达到计数器清零,则await返回true,如果等待超过了最大的等待时间,则返回false


简单理解为,先调用await()可以阻塞现成,当await(3) 当现成跑3次后就为0了,之后await阻塞的现成继续跑


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值