要实现两个带有 @Async 注解的方法按顺序执行,可以使用 CompletableFuture 来管理异步任务
的依赖关系。下面是一个完整的示例,展示了如何确保 method1 执行完成后,再执行 method2。
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
@Service
@EnableAsync
public class AsyncService {
@Async
public Future<String> method1() throws InterruptedException {
// 模拟耗时操作
Thread.sleep(2000);
String result = "Method 1 completed";
System.out.println(result);
return new CompletableFuture<>().completedFuture(result);
}
@Async
public Future<String> method2()
订阅专栏 解锁全文
1066

被折叠的 条评论
为什么被折叠?



