CompletableFuture多线程处理任务,等待所有线程处理完并返回结果
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Description:
* @Author: Alun
* @Date: 2023/12/21 19:43
* @Version: V1.0
*/
public class CompletableFutureDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("=============开始==============");
long start = System.currentTimeMillis();
List<CompletableFuture<String>> allCompletableFuture = new ArrayList<>();
// 线程池
ExecutorService executor = Executors.newWorkStealingPool(10);
for (int i = 0; i < 100; i++) {
int finalI = i+1;
// 异步线程
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
String str = task(finalI);
return str;
}, executor);
allCompletableFuture.add(completableFuture);
}
// 等待所有线程执行结束
System.out.println(allCompletableFuture.size());
for (CompletableFuture<String> stringCompletableFuture : allCompletableFuture) {
String str = stringCompletableFuture.get();
System.out.println("=====结果====" + str);
}
long time = System.currentTimeMillis() - start;
System.out.println("=============结束==============");
System.out.println(String.format("总耗时%s毫秒", time));
}
private static String task(Integer taskId) {
int time = 1000;
try {
Thread.sleep(time);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String str = String.format("任务号: %s, 执行时间: %s 毫秒", taskId, time);
System.out.println("=====任务====" + str);
return str;
}
}