pom配置文件中引入依赖
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
自定义线程池配置
package com.lyf.springboot.async.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* Created by Administrator on 2019/7/15 0015.
*/
@EnableAsync
@Configuration
public class ThreadPoolExecutorConfig {
@Bean(name = "myTaskExecutor",value = "myTaskExecutor")
public Executor taskExecutor() {
return Executors.newFixedThreadPool(10);
}
}
异步任务指定线程池
package com.lyf.springboot.async.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class AsyncTask {
@Async(value = "myTaskExecutor")
public void task1() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(1000);
long currentTimeMillis1 = System.currentTimeMillis();
log.info("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
@Async
/**使用springboot内部的线程池**/
public void task2() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(2000);
long currentTimeMillis1 = System.currentTimeMillis();
log.info("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
@Async(value = "myTaskExecutor")
public void task3() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(3000);
long currentTimeMillis1 = System.currentTimeMillis();
log.info("task3任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
}