异步任务
# 异步任务
# 1.CompletableFuture异步任务
启动异步任务,并指定交给哪个线程池执行。
public void test(){
CompletableFuture<Integer> future=CompletableFuture.supplyAsync(()->{
sout("执行任务");
int i=33;
return i;
},executor);
int result=future.get();
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
组合任务,创建两个CompletableFuture对象,然后可以指定同时完成/顺序执行。
使用CompletableFuture.allof(future1,future2,...)等待多个异步任务全部做完,然后futureAll.get()阻塞等待,都做完才继续下面的逻辑。
public void test(){
CompletableFuture<Integer> future1;
CompletableFuture<Integer> future2;
CompletableFuture<Integer> future3;
CompletableFuture<Void> allof=CompletableFuture.allof(future1,future2,future3);
allof.get();//阻塞时等待,才执行下面内容
}
1
2
3
4
5
6
7
2
3
4
5
6
7
所有异步任务方法Api:
- supplyAsync:包含返回值(供给后面的任务使用)+指定线程池
- future1.thenAcceptAsync((res)->{}):获取future1的返回值,并串行执行下一个异步任务
- CompletableFuture.allof(...).get():异步编排所有的future,并等待都执行完(只有调用get主线程才会等待)
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57