Java中的异步编程模型:CompletableFuture的使用
Java中的异步编程模型:CompletableFuture的使用
大家好,我是微赚淘客返利系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!
在Java中,异步编程是一种常见的编程范式,用于提高应用程序的响应性和吞吐量。Java 8引入了CompletableFuture
类,它是Java中实现异步编程的强大工具之一。CompletableFuture
提供了丰富的API,用于编写异步、非阻塞的代码。
CompletableFuture基础
CompletableFuture
是一个可以代表异步计算的结果的类。
import cn.juwatech.concurrent.CompletableFuture;
public class CompletableFutureExample {
public static void main(String[] args) {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 模拟长时间运行的任务
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Hello, CompletableFuture!";
});
future.thenAccept(System.out::println);
}
}
组合CompletableFuture
可以组合多个CompletableFuture
,以实现复杂的异步逻辑。
public class CombineFutures {
public static void main(String[] args) {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<String> combined = future1.thenCombine(future2, (s1, s2) -> s1 + " " + s2);
combined.thenAccept(System.out::println);
}
}
异常处理
在异步编程中处理异常是非常重要的。
public class ExceptionHandling {
public static void main(String[] args) {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Error!");
});
future.exceptionally(e -> {
System.out.println("Error: " + e.getMessage());
return "Default value";
}).thenAccept(System.out::println);
}
}
等待异步结果
有时需要等待异步操作的结果。
public class WaitForCompletion {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Done!";
});
String result = future.get(); // 阻塞直到有结果
System.out.println(result);
}
}
使用CompletableFuture进行并行处理
可以并行执行多个任务,并合并它们的结果。
public class ParallelProcessing {
public static void main(String[] args) {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> expensiveOperation(1));
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> expensiveOperation(2));
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2);
combinedFuture.thenRun(() -> {
System.out.println("Both tasks are completed");
});
}
private static String expensiveOperation(int number) {
// 模拟长时间运行的任务
try {
Thread.sleep(1000 * number);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Result of " + number;
}
}
CompletableFuture与Stream API结合
CompletableFuture
可以与Java 8的Stream API结合使用。
import java.util.stream.Stream;
import cn.juwatech.concurrent.CompletableFuture;
public class CompletableFutureWithStream {
public static void main(String[] args) {
Stream.of("Task1", "Task2", "Task3")
.map(task -> CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return task + " completed";
}))
.map(CompletableFuture::join)
.forEach(System.out::println);
}
}
定制线程池
可以为CompletableFuture
定制线程池。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import cn.juwatech.concurrent.CompletableFuture;
public class CustomThreadPool {
private static final ExecutorService executor = Executors.newFixedThreadPool(4);
public static void main(String[] args) {
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> "Hello", executor)
.thenApplyAsync(s -> s + " World", executor)
.thenAcceptAsync(System.out::println, executor);
future.join();
executor.shutdown();
}
}
总结
CompletableFuture
是Java中强大的异步编程工具,它提供了丰富的API来实现复杂的异步逻辑。通过使用CompletableFuture
,可以编写出更高效、更响应灵敏的Java应用程序。无论是组合多个异步任务、处理异常、等待异步结果,还是与Stream API结合使用,CompletableFuture
都是一个强大的工具。
本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了