CompletableFuture 异步线程使用

68 阅读1分钟

多任务异步任务 执行完毕使用

@Autowired
ThreadPoolTaskExecutor threadPoolTaskExecutor;

@Test
public void test() {

    long startTime = System.currentTimeMillis();
    final List<Integer> list = Arrays.asList(1, 5, 10);
    final List<Integer> result = new ArrayList<>();
    CompletableFuture.allOf(list.stream().map(v ->
            CompletableFuture.runAsync(() -> {
                try {
                    Thread.sleep(v * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                result.add(v);
            }, threadPoolTaskExecutor)
    ).toArray(CompletableFuture[]::new)).join();
    System.out.println("耗费时间:" +  (System.currentTimeMillis() - startTime));
    System.out.println(result);
    
}