标签:runnable test get main ble i+1 val 计时器 rup
title: 并发工具类:倒计时器-CountDownLatch
author: Enjoyitlife.top
date: 2019-10-01 10:51:33
summary: JUC包中的工具类CountDownLatch到底给我们提供了什么功能?
categories: Concurrent
tags:
CountDownLatch是JDK1.5提供一个并发编程辅助类,用于控制一个和多个线程进行等待,直到其他线程完成后在执行任务。
常用方法:
平常用于在创建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()+"^^^^");
}
}
运动员准备完毕后裁判发令,裁判发令后运动员开始跑步。
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("比赛完成!");
}
}
标签:runnable test get main ble i+1 val 计时器 rup
原文地址:https://www.cnblogs.com/enjoyitlife/p/11763793.html