• springboot-异步线程调用


    启动类:添加@EnableAsync注解

    @SpringBootApplication 

    @EnableAsync

    public class Application{

      public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

      }

    }

    Controller类

    @RequestMapping("")

    @RestController
    public class AsyncTaskController {

      @Autowired
      private AsyncTask asyncTask;

      @RequestMapping("")
      public String doTask() throws InterruptedException{
        long currentTimeMillis = System.currentTimeMillis();
        Future<String> task1 = asyncTask.task1();

        Future<String> task2 = asyncTask.task2();
        Future<String> task3 = asyncTask.task3();
        String result = null;
        for (;;) {
          if(task1.isDone() && task2.isDone() && task3.isDone()) {
          // 三个任务都调用完成,退出循环等待
          break;
          }
          Thread.sleep(1000);
        }

        long currentTimeMillis1 = System.currentTimeMillis();

        result = "task任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
        return result;

      }
    }


    异步任务类
    @Component
    public class AsyncTask {

      @Async
      public Future<String> task1() throws InterruptedException{
        long currentTimeMillis = System.currentTimeMillis();
        Thread.sleep(1000);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");

         return new AsyncResult<String>("task1执行完毕");
      }

      @Async
      public Future<String> task2() throws InterruptedException{
        long currentTimeMillis = System.currentTimeMillis();
        Thread.sleep(2000);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");

             return new AsyncResult<String>("task2执行完毕");
      }


      @Async
      public Future<String> task3() throws InterruptedException{
        long currentTimeMillis = System.currentTimeMillis();
        Thread.sleep(3000);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("task3任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");

             return new AsyncResult<String>("task3执行完毕");
      }

    }

    结果:

    1. task1任务耗时:1000ms
    2.  task2任务耗时:2001ms
    3.  task3任务耗时:3001ms

      task任务总耗时:4015ms

  • 相关阅读:
    三行代码搞定微信登录集成
    iptables命令
    Linux(centos)系统各个目录的作用详解 推荐
    Linux下Apache服务的查看和启动
    Linux使用退格键时出现^H ^?解决方法
    小程序:最难点For的wx:key
    linux 通过wol远程开机【转】
    linux wake on lan功能通过ethtool配置【转】
    设计模式小议:state【转】
    TCP/IP详解学习笔记(4)-ICMP协议,ping和Traceroute【转】
  • 原文地址:https://www.cnblogs.com/fantjesse/p/9447661.html
Copyright © 2020-2023  润新知