CountDownLatch

用来进行线程间的同步协作,等待所有线程完成倒计时

其中构造参数用来初始化等待计数值,await()用来等待计数归零,countDown()用来让计数减一

可以让主线程等待线程池中的所有线程执行完毕再运行

例如:王者荣耀游戏需要等所有玩家加载完毕才能开始

  1. private static void test2() throws InterruptedException {
  2. AtomicInteger num = new AtomicInteger(0);
  3. ExecutorService service = Executors.newFixedThreadPool(10, (r) -> {
  4. return new Thread(r, "t" + num.getAndIncrement());
  5. });
  6. CountDownLatch latch = new CountDownLatch(10);
  7. String[] all = new String[10];
  8. Random r = new Random();
  9. for (int j = 0; j < 10; j++) {
  10. int x = j;
  11. service.submit(() -> {
  12. for (int i = 0; i <= 100; i++) {
  13. try {
  14. Thread.sleep(r.nextInt(100));
  15. } catch (InterruptedException e) {
  16. }
  17. all[x] = Thread.currentThread().getName() + "(" + (i + "%") + ")";
  18. System.out.print("\r" + Arrays.toString(all));
  19. }
  20. latch.countDown();
  21. });
  22. }
  23. latch.await();
  24. System.out.println("\n游戏开始...");
  25. service.shutdown();
  26. }

future:

利用future让主线程获取其他多线程运行的返回结果

  1. private static void test3() throws InterruptedException, ExecutionException {
  2. RestTemplate restTemplate = new RestTemplate();
  3. log.debug("begin");
  4. ExecutorService service = Executors.newCachedThreadPool();
  5. CountDownLatch latch = new CountDownLatch(4);
  6. Future<Map<String, Object>> f1 = service.submit(() -> {
  7. Map<String, Object> response = restTemplate.getForObject("http://localhost:8080/order/{1}", Map.class, 1);
  8. return response;
  9. });
  10. Future<Map<String, Object>> f2 = service.submit(() -> {
  11. Map<String, Object> response1 = restTemplate.getForObject("http://localhost:8080/product/{1}", Map.class, 1);
  12. return response1;
  13. });
  14. Future<Map<String, Object>> f3 = service.submit(() -> {
  15. Map<String, Object> response1 = restTemplate.getForObject("http://localhost:8080/product/{1}", Map.class, 2);
  16. return response1;
  17. });
  18. Future<Map<String, Object>> f4 = service.submit(() -> {
  19. Map<String, Object> response3 = restTemplate.getForObject("http://localhost:8080/logistics/{1}", Map.class, 1);
  20. return response3;
  21. });
  22. System.out.println(f1.get());
  23. System.out.println(f2.get());
  24. System.out.println(f3.get());
  25. System.out.println(f4.get());
  26. log.debug("执行完毕");
  27. service.shutdown();
  28. }