@Async注解
我们都知道使用@Async标注在方法上,可以使该方法异步的调用执行。而所有异步方法的实际执行是交给TaskExecutor的。
关于@Async的基本知识不做讲解,只是对于使用过程中需要的注意的点做下强调。
最简单的使用
1.启动类添加@EnableAsync注解
package com.lara.springbootconfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
/**
* @author lara
*/
@SpringBootApplication
@EnableAsync
public class SpringBootConfigApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootConfigApplication.class, args);
}
}
2. 方法上添加@Async,类上添加@Component
package com.lara.springbootconfig.task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import java.util.Random;
import java.util.concurrent.Future;
/**
* @author lara
*/
@Component
@Slf4j
public class SyncTask {
public static Random random =new Random();
@Async
public Future<String> doTaskOne() throws Exception {
String threadName = Thread.currentThread().