CountDownLatch的使用

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

方法说明:

  1. await() 使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断

  2. countDown() 递减锁存器的计数,如果计数到达零,则释放所有等待的线程

  3. getCount() 返回当前计数

相关实例说明:

import org.springframework.stereotype.Component;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class CountDownLatchTest {
   public static void main(String[] args) throws InterruptedException {
      final CountDownLatch begin = new CountDownLatch(1);
      final CountDownLatch end = new CountDownLatch(10);

      ExecutorService es = Executors.newFixedThreadPool(10);
      for (int i = 0; i < 10; i++) {
         final int index = i + 1;
         es.submit(new Runnable() {
            public void run() {
               try {
                  begin.await(); // 等待指令
                  int s = (int)(Math.random() * 1000);
                  Thread.sleep(s);
                  System.out.println(String.format("No.%d到达,花费时间:%d毫秒!", index, s));
                  end.countDown();
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }
         });
      }
      System.out.println("各就位,预备跑!");
      begin.countDown();
      end.await();
      System.out.println("Game over!");

      es.shutdown();
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值