CountDownLatch
用来进行线程间的同步协作,等待所有线程完成倒计时
其中构造参数用来初始化等待计数值,await()用来等待计数归零,countDown()用来让计数减一
可以让主线程等待线程池中的所有线程执行完毕再运行
例如:王者荣耀游戏需要等所有玩家加载完毕才能开始
private static void test2() throws InterruptedException {AtomicInteger num = new AtomicInteger(0);ExecutorService service = Executors.newFixedThreadPool(10, (r) -> {return new Thread(r, "t" + num.getAndIncrement());});CountDownLatch latch = new CountDownLatch(10);String[] all = new String[10];Random r = new Random();for (int j = 0; j < 10; j++) {int x = j;service.submit(() -> {for (int i = 0; i <= 100; i++) {try {Thread.sleep(r.nextInt(100));} catch (InterruptedException e) {}all[x] = Thread.currentThread().getName() + "(" + (i + "%") + ")";System.out.print("\r" + Arrays.toString(all));}latch.countDown();});}latch.await();System.out.println("\n游戏开始...");service.shutdown();}
future:
利用future让主线程获取其他多线程运行的返回结果
private static void test3() throws InterruptedException, ExecutionException {RestTemplate restTemplate = new RestTemplate();log.debug("begin");ExecutorService service = Executors.newCachedThreadPool();CountDownLatch latch = new CountDownLatch(4);Future<Map<String, Object>> f1 = service.submit(() -> {Map<String, Object> response = restTemplate.getForObject("http://localhost:8080/order/{1}", Map.class, 1);return response;});Future<Map<String, Object>> f2 = service.submit(() -> {Map<String, Object> response1 = restTemplate.getForObject("http://localhost:8080/product/{1}", Map.class, 1);return response1;});Future<Map<String, Object>> f3 = service.submit(() -> {Map<String, Object> response1 = restTemplate.getForObject("http://localhost:8080/product/{1}", Map.class, 2);return response1;});Future<Map<String, Object>> f4 = service.submit(() -> {Map<String, Object> response3 = restTemplate.getForObject("http://localhost:8080/logistics/{1}", Map.class, 1);return response3;});System.out.println(f1.get());System.out.println(f2.get());System.out.println(f3.get());System.out.println(f4.get());log.debug("执行完毕");service.shutdown();}
