列举一
//测试一个简单的Java高并发示例,使用了CompletableFuture来并发地下载网页内容。在示例中,我们将并发下载多个网页,并在所有下载完成后进行处理。
public static void main(String[] args) {
List<String> urls = Arrays.asList(
"https://www.jaos.cn",
"https://www.mi.com",
"https://www.jd.com"
);
List<CompletableFuture<String>> downloadFutures = urls.stream()
.map(url -> CompletableFuture.supplyAsync(() -> downloadWebPage(url)))
.collect(Collectors.toList());
// 等待所有 CompletableFuture 任务完成
CompletableFuture<Void> allOf = CompletableFuture
.allOf(downloadFutures.toArray(new CompletableFuture[0]));
// 当所有下载完成后,处理结果
allOf.thenRun(() -> {
List<String> downloadedPages = downloadFutures.stream()
.map(future -> {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return null;
}
})
.collect(Collectors.toList());
downloadedPages.forEach(System.out::println);
});
// 阻止直到所有下载完成
allOf.join();
}
public static String downloadWebPage(String url) {
// 模拟下载网页
try {
Thread.sleep(1000); // 模拟网络延迟
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "内容 " + url;
}
列举二
//我们创建了一个包含数字的列表,然后使用CompletableFuture并行计算每个数字的平方。然后,我们使用CompletableFuture.allOf等待所有任务完成,然后提取各个任务的结果并打印出来。
public static void main(String[] args) throws InterruptedException, ExecutionException {
// 创建一个包含数字的列表
List<Integer> numbers = IntStream.range(1, 11).boxed().collect(Collectors.toList());
// 使用CompletableFuture并行计算每个数字的平方
List<CompletableFuture<Integer>> futures = numbers.stream()
.map(num -> CompletableFuture.supplyAsync(() -> computeSquare(num)))
.collect(Collectors.toList());
// 使用allOf等待所有任务完成
CompletableFuture<Void> allOf = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[0])
);
// 当所有任务完成后,提取各个任务的结果
CompletableFuture<List<Integer>> result = allOf.thenApply(v ->
futures.stream()
// .map(future -> future.join()) // 提取任务结果
.map(CompletableFuture::join) // 提取任务结果
.collect(Collectors.toList())
);
// 等待并获取最终结果
List<Integer> squaredNumbers = result.get();
// 打印结果
squaredNumbers.forEach(System.out::println);
}
private static int computeSquare(int num) {
// 模拟一个计算密集型任务
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return num * num;
}