多线程并发工具 CountDownLatch
作用:当有足够的线程运行后,再执行
****************************
相关类
CountDownLatch
public class CountDownLatch {
********
构造函数
public CountDownLatch(int count)
********
常用方法
public void await() //线程等待
public boolean await(long timeout, TimeUnit unit) throws InterruptedException //线程等待指定时间
public void countDown() //倒计数器减一
public long getCount() //倒计数器个数
**************************
示例
class Thread11 implements Runnable{
private CountDownLatch countDownLatch;
Thread11(CountDownLatch countDownLatch){
this.countDownLatch=countDownLatch;
}
@Override
public void run() {
try{
System.out.println("测试倒计数器:"+System.currentTimeMillis());
Thread.sleep(10000);
countDownLatch.countDown();
}catch (Exception e){
e.printStackTrace();
}
}
}
public class ThreadTest11 {
public static void main(String[] args){
CountDownLatch countDownLatch=new CountDownLatch(5);
Thread11 t=new Thread11(countDownLatch);
for(int i=0;i<5;i++){
Thread thread=new Thread(t);
thread.start();
}
try{
countDownLatch.await();
}catch (Exception e){
e.printStackTrace();
}
System.out.println();
System.out.println(Thread.currentThread().getName()+"运行结束"+System.currentTimeMillis());
}
}
**********************
控制台输出
测试倒计数器:1568860877230
测试倒计数器:1568860877229
测试倒计数器:1568860877230
测试倒计数器:1568860877230
测试倒计数器:1568860877229
main运行结束1568860887253