异步调用 简单理解就是不阻塞主线程,另一个 线程 执行操作。
第一种: Spring 异步方法,直接在方法上加注解 @Async
注意点:
1、在工程启动类加上 @EnableAsync注解,
2、该异步方法所在类要写在Spring管理的类中
3、要在其它类中调用该异步方法
4、有返回值时,返回类型一定是Future<xxx>
无返回值示例:
@Async ( “notifyExecutor” )
public void synchUpdateLmdmSupplierInfo(){
}
@Async括号中表示线程名称,通常情况下可以不写
有返回值示例
@Async
public Future<Integer> test1() {
return new AsyncResult <>( 10 )
}
第二种:jdk1.8及之后的Future,可以添加返回值,利用 jdk 原生CompletableFuture
代码示例如下:
ExecutorService executorService =Executors. newSingleThreadExecutor ();
CompletableFuture<String> future = CompletableFuture. supplyAsync (
new Supplier<String>() {
@Override
public String get() {
String msg;
try {
//以异步的方式调用方法
menthod();
msg = “发送成功” ;
} catch ( Exception e){
msg = “发送失败,失败的原因可能是:” + e.getMessage();
}
return msg;
}
}
,executorService );
future.thenAccept(e -> log .info( “sendMail返回参数” + e));
executorService.shutdown(); // 回收 线程池