Java CountDownLatch的使用

1、countDownLatch定义:它是java并发包里的,所以它肯定是用于java并发的场景;

2、它的主要方法就几个:

  CountDownLatch(int count) //实例化一个倒计数器,count指定计数个数;

  countDown() // 计数减一

  await();等待计数器到0,然后所有线程同时执行;

3、所以我使用它的一个场景就是模拟大量的并发请求,直接上代码:

@Service
public class InitThreadService {

  private static final Logger log = LoggerFactory.getLogger(InitThreadService.class);

  private static final int ThreadNum = 1000;

  @Autowired
  private ConcurrentService concurrentService;

  public void generateThread () {
    log.info("开始初始化线程,线程数量为:" + ThreadNum);

    try {
      CountDownLatch countDownLatch = new CountDownLatch(1); //计数器
      for (int i=0; i<ThreadNum; i++) {
      new Thread(new newThread(countDownLatch)).start();
    }
    //等线程创建完毕后,计数器归零;
    countDownLatch.countDown();
    } catch (Exception e) {
      log.info("初始化线程失败:" + e.fillInStackTrace());
    }

  }

  public class newThread implements Runnable {

    private final CountDownLatch startLatch;

    public newThread (CountDownLatch startLatch) {
      this.startLatch = startLatch;
    }

    @Override
    public void run() {

      try {
        startLatch.await();//线程都等待在这里
        log.info("线程开始干活了:" + System.currentTimeMillis());
        concurrentService.manageRobbing();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

    }
  }

}

  

原文地址:https://www.cnblogs.com/tengri-fighting/p/12689773.html