zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    js-格式化数字保留两位小数-带千分符
    java-byte[]图片在页面展示
    bootstrap-fileupload-上传文件控件
    css-让div永远在最底部
    hibernate-DetachedCriteria实现关联表条件复查
    eclipse-搭建maven的war项目集合spring注解方式
    spring-注解
    eclipse-mvn打包跳过junit测试类
    Spring-注解控件介绍
    java-读取类中的属性名称和值
  • 原文地址:https://www.cnblogs.com/fantjesse/p/9447661.html
Copyright © 2011-2022 走看看