一、CountDownLatch简介
CountDownLatch是一个同步工具类,用来协调多个线程之间的同步,或者说起到线程之间的通信(而不是用作互斥的作用)。
CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成一些任务,然后在CountDownLatch上等待的线程就可以恢复执行接下来的任务。
二、CountDownLatch的用法
CountDownLatch典型用法:1、某一线程在开始运行前等待n个线程执行完毕。将CountDownLatch的计数器初始化为new CountDownLatch(n),每当一个任务线程执行完毕,就将计数器减1 countdownLatch.countDown(),当计数器的值变为0时,在CountDownLatch上await()的线程就会被唤醒。一个典型应用场景就是启动一个服务时,主线程需要等待多个组件加载完毕,之后再继续执行。
CountDownLatch典型用法:2、实现多个线程开始执行任务的最大并行性。注意是并行性,不是并发,强调的是多个线程在某一时刻同时开始执行。类似于赛跑,将多个线程放到起点,等待发令枪响,然后同时开跑。做法是初始化一个共享的CountDownLatch(1),将其计算器初始化为1,多个线程在开始执行任务前首先countdownlatch.await(),当主线程调用countDown()时,计数器变为0,多个线程同时被唤醒。
三、CountDownLatch的不足
CountDownLatch是一次性的,计算器的值只能在构造方法中初始化一次,之后没有任何机制再次对其设置值,当CountDownLatch使用完毕后,它不能再次被使用。
四、代码实例
1、火箭发射
package com.guor.threads;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class CountDownLatchDemo implements Callable<Integer>{
static int threadCount = 15;
static int awaitMillisecond = 3000;
static CountDownLatch countDownLatch = new CountDownLatch(threadCount);
int id;
public CountDownLatchDemo(int id) {
this.id = id;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
boolean fireFlag = true;
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(threadCount);
List<Future<Integer>> futureList = new ArrayList<Future<Integer>>();
for(int i = 0; i< threadCount; i++) {
Future<Integer> future = newFixedThreadPool.submit(new CountDownLatchDemo(i));
futureList.add(future);
}
for(int i = 0; i< threadCount; i++) {
Future<Integer> future = futureList.get(i);
if(0 == future.get()) {
fireFlag = false;
break;
}
}
if(true == fireFlag) {
System.out.println(getCurrentTime() + "fire.");
}else {
System.out.println(getCurrentTime() + "countDownLatch.await().");
//设置超时时间awaitMillisecond
countDownLatch.await(awaitMillisecond, TimeUnit.MILLISECONDS);
System.out.println(getCurrentTime() + Thread.currentThread().getName() + ", 线程阻塞");
//线程阻塞
countDownLatch.await();
System.out.println(getCurrentTime() + "thread contains error, do not fire.");
}
newFixedThreadPool.shutdown();
}
@Override
public Integer call() {
try {
if(id < 9) {
System.out.println(getCurrentTime() + Thread.currentThread().getName()+", 检查完毕.");
countDownLatch.countDown();
return 1;
}else {
//int a = 1/0;
System.out.println(getCurrentTime() + Thread.currentThread().getName()+", 存在异常,检查中...");
Thread.sleep(awaitMillisecond);
System.out.println(getCurrentTime() + Thread.currentThread().getName()+", 检查失败.");
return 0;
}
}catch (Exception e) {
System.out.println("call exception.");
return 0;
}
}
private static String getCurrentTime() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String format = sdf.format(date);
String ret = "[" + format + "] ";
return ret;
}
}
2、控制台输出
(1)发射成功
(2)发射失败
往期精彩内容: