java 创建异步任务
时间: 2023-12-13 09:00:07 浏览: 85
在 Java 中创建异步任务可以使用多线程或者 CompletableFuture。
1. 多线程
使用多线程可以在后台执行耗时操作,避免阻塞主线程。可以使用 Thread 或者 ExecutorService 来创建线程,例如:
```java
new Thread(() -> {
// 执行耗时操作
}).start();
```
或者使用 ExecutorService:
```java
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
// 执行耗时操作
});
executor.shutdown();
```
2. CompletableFuture
CompletableFuture 是 Java 8 新增的异步编程工具,可以很方便地创建异步任务,例如:
```java
CompletableFuture.supplyAsync(() -> {
// 执行耗时操作
return result;
}).thenAcceptAsync(result -> {
// 处理结果
});
```
其中 supplyAsync 方法返回一个 CompletableFuture 对象,表示异步任务。thenAcceptAsync 方法接收异步任务的结果,并在另一个线程中处理结果。可以通过 thenApplyAsync 方法对结果进行转换,或者使用 thenComposeAsync 方法将多个异步任务按顺序执行。
阅读全文
相关推荐


















