title: 并发工具类:倒计时器-CountDownLatch
author: Enjoyitlife.top
date: 2019-10-01 10:51:33
summary: JUC包中的工具类CountDownLatch到底给我们提供了什么功能?
categories: Concurrent
tags:
- Concurrent-Tools
并发工具类:倒计时器-CountDownLatch
CountDownLatch是JDK1.5提供一个并发编程辅助类,用于控制一个和多个线程进行等待,直到其他线程完成后在执行任务。
常用方法:
- CountDownLatch latch= new CountDownLatch(10); 构造方法,设定计数值,即要等待的线程数量。
- void countDown() 计数器的值减1,直到为0
- void await() 阻塞等待,直到计数器的值为0
- long getCount() 获取当前计数器的值
应用场景 1:实现多个N个线程并行运行
平常用于在创建N个线程来,验证接口的性能。
public class CountDownLatchTest {
public static void main(String[] args) {
CountDownLatch latch= new CountDownLatch(5);
try {
for(int i=0;i<5;i++) {
new Thread(new Runnable() {
@Override
public void run() {
CountDownLatchTest.sayThreadName();
}
}).start();
}
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/***
*模拟真正接口
*/
public static void sayThreadName() {
System.out.println(System.currentTimeMillis()+"^^"+Thread.currentThread().getName()+"^^^^");
}
}
应用场景2:等待N个线程完成任务后在触发其他操作
运动员准备完毕后裁判发令,裁判发令后运动员开始跑步。
public class AthleticMeeting {
public static void main(String[] args) throws InterruptedException {
//准备队列
CountDownLatch readLatch = new CountDownLatch(8);
//结束队列
CountDownLatch endLatch = new CountDownLatch(8);
//教练队列
CountDownLatch refereeLatch=new CountDownLatch(1);
for(int i=0;i<8;i++) {
final int payerId=i+1;
Thread thread= new Thread(new Runnable() {
@Override
public void run() {
try {
Long readyCosts=new Double(Math.random()*5000).longValue();
Thread.sleep(readyCosts);
System.out.println(payerId+"号运动员耗时"+readyCosts+"毫秒准备完毕!");
readLatch.countDown();
refereeLatch.await();
Long runCost=new Double(Math.random()*5000).longValue();
Thread.sleep(runCost);
System.out.println(payerId+"号运动员耗时"+runCost+"毫秒完成比赛!");
endLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
readLatch.await();
System.out.println("所有运动员准备完毕!");
refereeLatch.countDown();
System.out.println("裁判发动发令枪!");
endLatch.await();
System.out.println("比赛完成!");
}
}
原文地址:https://www.cnblogs.com/enjoyitlife/p/11763793.html
时间: 2024-11-05 17:33:29