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

posted @   张占岭  阅读(2520)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
历史上的今天:
2011-12-27 VS远程调试(在IIS中打开网站,进入VS中的断点)
点击右上角即可分享
微信分享提示