CountDownLatch说明

CountDownLatch说明

介绍

一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

用给定的计数 初始化 CountDownLatch。由于调用了 countDown() 方法,所以在当前计数到达零之前,await 方法会一直受阻塞。之后,会释放所有等待的线程,await 的所有后续调用都将立即返回。这种现象只出现一次——计数无法被重置。如果需要重置计数,请考虑使用 CyclicBarrier。

CountDownLatch 是一个通用同步工具,它有很多用途。将计数 1 初始化的 CountDownLatch 用作一个简单的开/关锁存器,或入口:在通过调用 countDown() 的线程打开入口前,所有调用 await 的线程都一直在入口处等待。用 N 初始化的 CountDownLatch 可以使一个线程在 N 个线程完成某项操作之前一直等待,或者使其在某项操作完成 N 次之前一直等待。

CountDownLatch 的一个有用特性是,它不要求调用 countDown 方法的线程等到计数到达零时才继续,而在所有线程都能通过之前,它只是阻止任何线程继续通过一个 await。

示例

package com.chen.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;



public class CountDownLatchTest {
	
	public static void main(String[] args) {
		CountDownLatchTest countDownLatchTest = new CountDownLatchTest();
		AtomicInteger atomicInteger = new AtomicInteger(100);
		try {
			countDownLatchTest.test01(2,atomicInteger);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public void test01(int t_number,AtomicInteger workTask) throws InterruptedException{
		CountDownLatch startSignal = new CountDownLatch(1);
		CountDownLatch doneSignal = new CountDownLatch(t_number);
		
		Worker worker = new Worker(startSignal, doneSignal,workTask);
		for(int i = 0;i < t_number;i++){
			Thread thread = new Thread(worker);
			thread.start();
		}
		
		startSignal.countDown();
		System.out.println("工作开始===========");
		doneSignal.await();
		System.out.println("工作结束===========");
	}
	
	class Worker implements Runnable{

		private CountDownLatch startSignal;
		private CountDownLatch doneSignal;
		
		private AtomicInteger workTask;
		
		public Worker(CountDownLatch startSignal,CountDownLatch doneSignal,AtomicInteger workTask) {
			this.startSignal = startSignal;
			this.doneSignal = doneSignal;
			this.workTask = workTask;
		}
		
		@Override
		public void run() {
			try {
				startSignal.await();
				doWork();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
		public void doWork(){
			
			System.out.println(Thread.currentThread().getName()+"开始工作");
			while(workTask.get() != 0){
				int result = workTask.decrementAndGet();
				System.out.println(Thread.currentThread().getName()+":"+result);
				
				try {
					Thread.sleep(1000);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			System.out.println(Thread.currentThread().getName()+"工作结束");
			doneSignal.countDown();
		}
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值