Future和AsyncResult的异步和同步

Future和AsyncResult是什么?后面再看!

先直接上代码:

Demo 1

  1. 第一步,用最简单的方法生成一个可运行的Spring Boot项目:https://start.spring.io/ (Dependencies(依赖)加个Spring Web
  2. 生成的项目中,找到启动类DemoApplication,添加异步注解@EnableAsync
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableAsync
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  1. 新建 FutureService.java,里面有三个方法,返回值用 AsyncResult 包装一下,为了方便看效果,加上一些日志
package com.example.demo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

@Service
@Slf4j
public class FutureService {
    @Async
    public Future jobOne() throws InterruptedException {
        System.out.println("job 1 start...");
        long start = System.currentTimeMillis();
        Thread.sleep(2000);
        long end = System.currentTimeMillis();
        System.out.println("job 1 completed, it took " + (end - start));
        return new AsyncResult<>( "job 1 success");
    }
    @Async
    public Future jobTwo() throws InterruptedException {
        System.out.println("job 2 start...");
        long start = System.currentTimeMillis();
        Thread.sleep(500);
        long end = System.currentTimeMillis();
        System.out.println("job 2 completed, it took " + (end - start));
        return new AsyncResult<>( "job 2 success");
    }
    @Async
    public Future jobThree() throws InterruptedException {
        System.out.println("job 3 start...");
        long start = System.currentTimeMillis();
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        System.out.println("job 3 completed, it took "+ (end - start));
        return new AsyncResult<>( "job 3 success");
    }
}
  1. 新建 DemoControllerl.java,调用 FutureService 里的三个方法
package com.example.demo.controller;

import com.example.demo.service.FutureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
public class DemoController {
    @Autowired
    private FutureService futureService;

    @RequestMapping("/test")
    public String test() throws InterruptedException, ExecutionException {
        long start = System.currentTimeMillis();
        Future f1 = futureService.jobOne();
        Future f2 = futureService.jobTwo();
        Future f3 = futureService.jobThree();
        // 三个方法都执行完毕才继续执行后面代码
        while (!f1.isDone() || !f2.isDone() || !f3.isDone()){
            System.out.println("Waiting....");
            Thread.sleep(300);
        }
        // 三个方法都执行完毕
        long end = System.currentTimeMillis();
        System.out.println("Result 1: " + f1.get());
        System.out.println("Result 2: " + f2.get());
        System.out.println("Result 3: " + f3.get());
        System.out.println("Execution Time : " + (end - start));
        return "success";
    }
}

  1. 运行启动类 DemoApplication,启动成功后访问 http://localhost:8080/test, 可以看到以下效果:
job 1 start...
job 2 start...
Waiting....
job 3 start...
Waiting....
job 2 completed, it took 501
Waiting....
Waiting....
job 3 completed, it took 1000
Waiting....
Waiting....
Waiting....
job 1 completed, it took 2002
Result 1: job 1 success
Result 2: job 2 success
Result 3: job 3 success
Execution Time : 2114

从打印的日志可以看出来,并不是按照三个方法调用的顺序,一个方法执行完再执行下一个方法,三个方法的运行时间:501、1000、2002,而总的运行时间为2114,这个例子中,三个方法是异步执行的。。

Demo 2

还是用上面的代码,但是 DemoController 是代码顺序稍微调整一下:按照平时的习惯,执行一个方法,输出结果。

@RestController
public class DemoController {
    @Autowired
    private FutureService futureService;

    @RequestMapping("/test")
    public String test() throws InterruptedException, ExecutionException {
        long start = System.currentTimeMillis();
        Future f1 = futureService.jobOne();
        System.out.println("Result 1: " + f1.get());
        Future f2 = futureService.jobTwo();
        System.out.println("Result 2: " + f2.get());
        Future f3 = futureService.jobThree();
        System.out.println("Result 3: " + f3.get());
        long end = System.currentTimeMillis();
        System.out.println("Execution Time : " + (end - start));
        return "success";
    }
}

重新运行启动类 DemoApplication,可以看到以下结果:

job 1 start...
job 1 completed, it took 2005
Result 1: job 1 success
job 2 start...
job 2 completed, it took 502
Result 2: job 2 success
job 3 start...
job 3 completed, it took 1004
Result 3: job 3 success
Execution Time : 3516

这次的输出结果,和没有用Future和AsyncResult的方法是一样的效果,每个方法按顺序执行,一个结果后再执行下一个。

概念

Future

Future是 java.util.concurrent 包里的一个接口
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html

  • cancel(boolean mayInterruptIfRunning): boolean
  • get()
  • get(long timeout, TimeUnit unit)
  • isCancelled(): boolean
  • isDone(): boolean

2022.9.14 更新
最近由于项目上对一些慢接口的优化,把很多接口加上了@Async,上线运行一段时间后,发现线程数量激增!!!

@Async默认使用Spring的SimpleAsyncTaskExecutor:

TaskExecutor implementation that fires up a new Thread for each task, executing it asynchronously.

每提交一个任务,就会创建一个线程,能不炸吗?
解决方法: @Async(value="customExecutor"), value参数传入自定义的线程池。

你可能感兴趣的:(Future和AsyncResult的异步和同步)