有返回结果的supplyAsync
此方法第二个参数需要传入一个线程池
代码案例
private static ExecutorService pool;
public static void main(String[] args) throws Exception{
// 初始化线程池
pool = new ThreadPoolExecutor(2, 2, 16000, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 模拟一个耗时的计算
try {
TimeUnit.SECONDS.sleep(6);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
System.out.println("2222");
return "Hello, CompletableFuture!";
});
CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> {
// 模拟一个耗时的计算
try {
TimeUnit.SECONDS.sleep(6);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
System.out.println("555555");
return "Hello, CompletableFuture11111!";
});
CompletableFuture.allOf(future, future2).join(); // 使用join方法等待所有任务执行完成
System.out.println("33333" + future.get()); // 使用 get 方法阻塞等待结果
System.out.println("4444" + future2.get());
pool.shutdown();
System.out.println("111111");
}
没有返回结果的runAsync
// 初始化线程池
pool = new ThreadPoolExecutor(2, 2, 16000, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
// 模拟一个耗时的操作
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
System.out.println("Task completed!");
});
future.join();
处理结果的方法thenAccept
此方法需要先调用join方法等待异步执行完成,否则可能会获取不到结果
// 初始化线程池
pool = new ThreadPoolExecutor(2, 2, 16000, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
CompletableFuture<String> faultyFuture = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "Something went wrong1111!";
}, pool);
faultyFuture.join();
faultyFuture.thenAccept(result -> {
System.out.println("Result: " + result);
});
pool.shutdown();
使用 exceptionally 处理异常
// 初始化线程池
pool = new ThreadPoolExecutor(2, 2, 16000, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
CompletableFuture<String> faultyFuture = CompletableFuture.supplyAsync(() -> {
// 模拟一个耗时的操作
try {
TimeUnit.SECONDS.sleep(6);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
throw new RuntimeException("Something went wrong!");
}, pool);
faultyFuture.exceptionally(ex -> {
System.err.println("Exception caught: " + ex.getMessage());
return "Default value";
}).thenAccept(result -> {
System.out.println("Result after handling exception: " + result);
});
pool.shutdown();
组合多个 CompletableFuture
使用 thenCompose 和 thenCombine
// 初始化线程池
pool = new ThreadPoolExecutor(2, 2, 16000, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello", pool);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World", pool);
CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (s1, s2) -> s1 + ", " + s2);
combinedFuture.thenAccept(result -> {
System.out.println(result); // 输出: Hello, World
});
pool.shutdown();