springboot异步执行方法
完整代码
package com.linux.linuxtest.controller;
import lombok.SneakyThrows;
import java.util.concurrent.CompletableFuture;
public class CompletableFutureCompose {
//添加方法注解
@SneakyThrows
public static void thenRunAsync() {
//执行第一个任务
CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> {
for (int i = 50 ; i < 100;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.err.println(i);
}
});
//执行第二个任务
CompletableFuture<Integer> cf2 = CompletableFuture.runAsync(() -> {
for (int i = 50 ; i > 0;i--){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(i);
}
}).thenCompose(v -> CompletableFuture.supplyAsync(() -> {
// 如果需要cf2完成后执行某些操作,可以在这里写上你的代码
System.out.println("任务2执行完毕");
return 1;
}));
//等待任务1执行完成
System.out.println("cf1结果->" + cf1.get());
//等待任务2执行完成,并拿到返回结果
System.out.println("cf2结果->" + cf2.get());
}
public static void main(String[] args) {
thenRunAsync();
}
}
执行完成后打印结果: