Java线程--CountDownLatch倒计数器

CountDownLatch倒计数器

目录

CountDownLatch倒计数器

CountDownLatch场景

CountDownLatch原理

CountDownLatch示例 


CountDownLatch场景

 想要做当前事情之前,必须具备前期的若干事件都准备完毕,当前事件才能进行。用程序来说,就是:

当前线程处于阻塞状态,必须等到其它的若干线程都运行完毕之后,当前线程才被唤醒得以执行。

CountDownLatch原理

 CountDownLatch源码

CountDownLatch类的源码:内部私有类Sync继承AQS,最主要的两个方法await()、countDown()。CountDownLatch类是共享模式的同步器。至于AQS,concurrent包的基石,建议参考https://www.cnblogs.com/chengxiao/p/7141160.html

CountDownLatch类其实是实现了线程之间的通讯,其背后实现的本质是利用了Object对象的wait()、notify()、notifyAll()方法来达到线程之间的通讯。

await()方法,功能类似Object的wait()方法,进行当前线程的阻塞。

countDown()方法,其内部逻辑是计数递减1,然后判断计数是否为零。直到计数当前为零,才唤醒阻塞的线程。功能类似Object的notify()、notifyAll()方法

CountDownLatch示例 

import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.concurrent.atomic.*;

class PrepareEvent implements Runnable
{
	private CountDownLatch c ;
	public PrepareEvent(CountDownLatch c){
		this.c = c ;
	}

	public void run(){
		try{
			long time = (long)(Math.random() * 5000); //模拟前期准备事件耗时
			Thread.sleep(time); 
			String tName = Thread.currentThread().getName();
			System.out.println(tName+"' working time is: "+time);
		}catch(InterruptedException e){}

		c.countDown();
	}
}

public class CountDownLatchTest 
{
	public static void main(String[] args) 
	{
		int count = 5 ;//计数5
		CountDownLatch c = new CountDownLatch(count);

		Thread[] ts = new Thread[count];

		System.out.println("CountDownLatch init, now count is: "+c.getCount()+"\n\r");
		System.out.println("because Of await(), main blocking...\n\r");
		
		for(int i=count-1; i>=0; i--){
			ts[i] = new Thread(new PrepareEvent(c),"T"+i);
			ts[i].start();
		}
		
		try{
			c.await();//这里阻塞,直至计数降为零
		}catch(InterruptedException e){}

		System.out.println("     \n\rafter await(), main continue...\n\r");
		System.out.println("CountDownLatch used, now count is: "+c.getCount()+"\n\r");

	}
}

运行结果如下:

CountDownLatch init, now count is: 5

because Of await(), main blocking...

T3' working time is: 1099
T2' working time is: 3320
T0' working time is: 3448
T4' working time is: 3647
T1' working time is: 3825

after await(), main continue...

CountDownLatch used, now count is: 0

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值