zoukankan      html  css  js  c++  java
  • java~@Async异步功能

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

    异步入口

    @EnableAsync
    

    具体的异步方法

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

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

    带有返回值的异步

    @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),所以会租塞,直到有返回结果为止。

  • 相关阅读:
    面试题--赵银科技
    面试题--乐视.滴滴
    面试题--CVTE
    面试题--美团
    面试题--百度
    面试题--京东 有用
    mybatis的执行流程 #{}和${} Mysql自增主键返回 resultMap 一对多 多对一配置
    SpringMVC第一天
    LeetCode -- Maximum Product Subarray
    LeetCode -- Product of Array Except Self My Submissions Question
  • 原文地址:https://www.cnblogs.com/lori/p/10186888.html
Copyright © 2011-2022 走看看