并行神器CompletableFuture
2023-02-02 本文已影响0人
不知不怪
package com.gzz;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CompletableFutureTest {
static ExecutorService executor = Executors.newFixedThreadPool(10);
static Random random = new Random();
public static void main(String[] args) {
long start = System.currentTimeMillis();
CompletableFuture<Void> task1 = CompletableFuture.runAsync(() -> task(1), executor);
CompletableFuture<Void> task2 = CompletableFuture.runAsync(() -> task(3), executor);
CompletableFuture<Void> task3 = CompletableFuture.runAsync(() -> task(4), executor);
CompletableFuture<Void> task4 = CompletableFuture.runAsync(() -> task(2), executor);
CompletableFuture.allOf(task1, task2, task3, task4).thenRun(() -> {
long end = System.currentTimeMillis();
log.info("完成全部任务耗时{}毫秒", end - start);
executor.shutdown();
});
}
private static void task(int i) {
log.info("开始做任务{}", i);
long start = System.currentTimeMillis();
try {
TimeUnit.MILLISECONDS.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
log.info("完成任务{}耗时{}毫秒", i, end - start);
}
}