java多线程之CountDownLatch类基本用法

java.util.concurrent.CountDownLatch类是一个同步计数器,构造时传入int参数,该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1,计数器大于0 时,await()方法会阻塞程序继续执行。
1.构造方法参数指定了计数的次数
2.countDown方法,当前线程调用此方法,则计数减一
3.awaint方法,调用此方法会一直阻塞当前线程,直到计时器的值为0

package cn.baokx;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

class SubThread implements Runnable{
	private CountDownLatch downLatch;
	private String name;
	
	public SubThread(CountDownLatch downLatch,String name){
		this.downLatch = downLatch;
		this.name = name;
	}

	@Override
	public void run() {
		System.out.println(this.name+" is working...");
		try {
			TimeUnit.SECONDS.sleep(new Random().nextInt(10));
			System.out.println(this.name + " has finished its working...");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			this.downLatch.countDown();
		}
	}
}

public class CountDownLatchTest {
	public static void main(String[] args) {
		CountDownLatch downLatch = new CountDownLatch(4);
		SubThread st1 = new SubThread(downLatch,"subThread1");
		SubThread st2 = new SubThread(downLatch,"subThread2");
		SubThread st3 = new SubThread(downLatch,"subThread3");
		SubThread st4 = new SubThread(downLatch,"subThread4");
		
		System.out.println("MainThread is wating...");
		new Thread(st1).start();
		new Thread(st2).start();
		new Thread(st3).start();
		new Thread(st4).start();
		try {
			downLatch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("All subThread has finished,MainThread can begin to checking...");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值