一、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)發射失敗

往期精彩內容:
Java知識體系總結(2021版)
超詳細的springBoot學習筆記
Java多執行緒基礎知識總結(絕對經典)
Java面試題總結(附答案)
Vue基礎知識總結(絕對經典)
常見資料結構與演算法整理總結
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/260402.html
標籤:java
上一篇:springboot啟動原始碼決議(三):初始化啟動背景關系、初始化監聽器串列、發布開始啟動事件
下一篇:Web全堆疊~34.CAS
