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

猜你喜欢

转载自blog.csdn.net/mmlz00/article/details/83718943