版本:springboot2.1.1
1.配置類(lèi)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync//開(kāi)啟異步任務(wù)支持
public class ThreadConfig {
/**
*配置線程池,可配置多個(gè)線程池,并指定bean名稱(chēng)
* @return
*/
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 設(shè)置核心線程數(shù)
executor.setCorePoolSize(5);
// 設(shè)置最大線程數(shù)
executor.setMaxPoolSize(10);
// 設(shè)置隊(duì)列容量
executor.setQueueCapacity(20);
// 設(shè)置線程活躍時(shí)間(秒)
executor.setKeepAliveSeconds(60);
// 設(shè)置默認(rèn)線程名稱(chēng)
executor.setThreadNamePrefix("thread-");
// 設(shè)置拒絕策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任務(wù)結(jié)束后再關(guān)閉線程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
@Bean(name = "thread")
public TaskExecutor taskExecutor1() {
......
}
}
2.任務(wù)執(zhí)行類(lèi)(只需在需要異步的方法上添加@Async注解)
@Slf4j
@Service
public class TestThread{
//通過(guò)指定的不同value值,使用對(duì)應(yīng)bean名稱(chēng)的線程池
//不指定使用缺省線程池
@Async(value = "thread")
public void runThread(Integer n){
log.info("線程。。。。。"+n);
}
}
3.調(diào)用類(lèi)
@RestController
public class TestThreadController {
@Autowired
private TestThread testThread;
@RequestMapping("test")
public String test() {
for(int i=0;i<10;i++){
testThread.runThread(i);
}
return "異步執(zhí)行中......";
}
}