当使用@Async
注解异步方法时,要注意异步方法不能直接返回值,因为主线程在调用异步方法后不会等待异步方法的执行完成。通常情况下,异步方法返回void
类型,要获得返回结果可通过回调函数、CompletableFuture
或其他方式来处理。
@Service
public class AsyncService {
private static final Logger log = LoggerFactory.getLogger(AsyncService.class);
@Async
public CompletableFuture<String> performAsyncTask() {
try {
Thread.sleep(2000);
String str="我是执行异步方法后的返回值GGB";
return CompletableFuture.completedFuture(str);
} catch (InterruptedException e) {
log.error("异步方法执行出现异常"+e.getMessage());
return CompletableFuture.completedFuture(e.getMessage());
}
}
}
public class AaynTest {
@Autowired
private AsyncService asyncService;
@Test
public void testAsync2() {
System.out.println("调用异步方法之前");
CompletableFuture<String> completableFuture = asyncService.performAsyncTask();
completableFuture.thenAccept(str->{
System.out.println("接受到了异步方法返回的结果: "+str);
});
System.out.println("调用异步方法之后");
}
}
调用异步方法之前
调用异步方法之后
接受到了异步方法返回的结果: 我是执行异步方法后的返回值GGB