|
| 1 | +package org.geekbang.time.commonmistakes.concurrenttool.multiasynctasks; |
| 2 | + |
| 3 | +import lombok.extern.slf4j.Slf4j; |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.List; |
| 7 | +import java.util.concurrent.*; |
| 8 | +import java.util.stream.Collectors; |
| 9 | +import java.util.stream.IntStream; |
| 10 | + |
| 11 | +@Slf4j |
| 12 | +public class CommonMistakesApplication { |
| 13 | + |
| 14 | + private static ExecutorService threadPool = Executors.newFixedThreadPool(10); |
| 15 | + |
| 16 | + public static void main(String[] args) { |
| 17 | + test1(); |
| 18 | + } |
| 19 | + |
| 20 | + private static void test1() { |
| 21 | + long begin = System.currentTimeMillis(); |
| 22 | + List<Future<Integer>> futures = IntStream.rangeClosed(1, 4) |
| 23 | + .mapToObj(i -> threadPool.submit(getAsyncTask(i))) |
| 24 | + .collect(Collectors.toList()); |
| 25 | + List<Integer> result = futures.stream().map(future -> { |
| 26 | + try { |
| 27 | + return future.get(2, TimeUnit.MILLISECONDS); |
| 28 | + } catch (Exception e) { |
| 29 | + e.printStackTrace(); |
| 30 | + return -1; |
| 31 | + } |
| 32 | + }).collect(Collectors.toList()); |
| 33 | + log.info("result {} took {} ms", result, System.currentTimeMillis() - begin); |
| 34 | + } |
| 35 | + |
| 36 | + private static Callable<Integer> getAsyncTask(int i) { |
| 37 | + return () -> { |
| 38 | + TimeUnit.SECONDS.sleep(i); |
| 39 | + return i; |
| 40 | + }; |
| 41 | + } |
| 42 | + |
| 43 | + private static void test2() { |
| 44 | + long begin = System.currentTimeMillis(); |
| 45 | + int count = 4; |
| 46 | + List<Integer> result = new ArrayList<>(count); |
| 47 | + CountDownLatch countDownLatch = new CountDownLatch(count); |
| 48 | + IntStream.rangeClosed(1, count).forEach(i -> threadPool.execute(executeAsyncTask(i, countDownLatch, result))); |
| 49 | + try { |
| 50 | + countDownLatch.await(3, TimeUnit.SECONDS); |
| 51 | + } catch (InterruptedException e) { |
| 52 | + e.printStackTrace(); |
| 53 | + } |
| 54 | + log.info("result {} took {} ms", result, System.currentTimeMillis() - begin); |
| 55 | + } |
| 56 | + |
| 57 | + private static Runnable executeAsyncTask(int i, CountDownLatch countDownLatch, List<Integer> result) { |
| 58 | + return () -> { |
| 59 | + try { |
| 60 | + TimeUnit.SECONDS.sleep(i); |
| 61 | + } catch (InterruptedException e) { |
| 62 | + e.printStackTrace(); |
| 63 | + } |
| 64 | + synchronized (result) { |
| 65 | + result.add(i); |
| 66 | + } |
| 67 | + countDownLatch.countDown(); |
| 68 | + }; |
| 69 | + } |
| 70 | +} |
| 71 | + |
0 commit comments