java~@Async异步功能

匿名 (未验证) 提交于 2019-12-02 20:59:24

@Async注解,可以实现异步处理的功能,它可以有返回值,或者直接在新线程时并行执行一个任务,对于异步来说,它的执行是有条件的,你需要把异步代码块放在单独的类里,当spring在注入时,才不会相互影响,因为异步是一个比较特殊的代理。

  1. 异步入口
@EnableAsync
  1. 具体的异步方法
/**  * 异常的类型应该和同步执行的类分开,这样在ioc建立时不会相互干扰  */ @Service public class MessageService {   @Async   public void msg1() throws Exception {      Thread.sleep(5000L);     System.out.println("async1:" + LocalDateTime.now() +         ",id:" + Thread.currentThread().getId());   } }

上面代码中的异步,是一个没有返回值的,一般像发送消息可以采用这种方式。

  1. 带有返回值的异步
@Async   public Future<String> asyncMethodWithReturnType() {     System.out.println("Execute method asynchronously - "         + Thread.currentThread().getName());     try {       Thread.sleep(5000);       return new AsyncResult<String>("hello world !!!!");     } catch (InterruptedException e) {       //     }     return null;   }

这种会返回一个委托对象Future,我们如果希望得到它的返回时,需要在主程序中去监听它,就是写在循环,去等待它的返回结果。

Future<String> future = messageService.asyncMethodWithReturnType();      while (true) { ///这里使用了循环判断,等待获取结果信息       if (future.isDone()) { //判断是否执行完毕         System.out.println("Result from asynchronous process - " + future.get());         break;       }       System.out.println("Continue doing something else. ");       System.out.println("main end:" + LocalDateTime.now() +           ",id:" + Thread.currentThread().getId());      }

上面代码主程序在执行到异步方法时,由于遇到了while(true),所以会租塞,直到有返回结果为止。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!