java拓展----CountDownLatch同步辅助类

同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一
个或多个线程一直等待。

• countDown() 当前线程调此方法,则计数减一(建议放在 finally里执
• await(), 调用此方法会一直阻塞当前线程,直到计时器的值为0

一下是CountDownLatch同步辅助类的使用Demo:

 1 package com.demo.singleton;
 2 
 3 import java.util.concurrent.CountDownLatch;
 4 
 5 /**
 6  *CountDownLatch是一个同步辅助类,用于开线程进行方法的性能测试。
 7  */
 8 public class CountDownLatchTest {
 9     public static void main(String[] args) throws InterruptedException {
10         //定义一个计数常量count
11         int count = 10;
12         //创建一个同步辅助对象
13         final CountDownLatch countDownLatch = new CountDownLatch(count);
14         //记录起始时间
15         long l1 = System.currentTimeMillis();
16         //循环创建线程
17         for(int i=0;i<count;i++){
18             new Thread(new Runnable() {
19                 @Override
20                 public void run() {
21                     for(int i =0;i<1000000000;i++){
22                         try {
23                             Singleton2.getSingleton();
24                         } catch (Exception e) {
25                             e.printStackTrace();
26                         }
27                     }
28                     //每单一个线程执行结束,计数器就减一
29                     countDownLatch.countDown();
30                 }
31             }).start();
32         }
33         //主线程等待,知道计数器为0
34         countDownLatch.await();
35         long l2 = System.currentTimeMillis();
36         System.out.println("最后执行时间:"+(l2-l1));
37     }
38 }
原文地址:https://www.cnblogs.com/bananafish/p/9946154.html