Java 中异步调用

异步调用简单理解就是不阻塞主线程,另一个线程执行操作。

第一种: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(); // 回收线程池

posted @ 2022-06-09 15:40  海棠匠心  阅读(2977)  评论(0)    收藏  举报