SpringBoot 集成线程池
1、项目结构说明:
2、线程池核心代码:
package com.zzg.threadpool.config;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
*
* @ClassName: ThreadPoolConfig
* @Description: 线程池配置类
* @author: **** -zzg
* @date: 2019年4月9日 上午10:31:49
*
* @Copyright: 2019 www.digipower.cn
* 注意:本内容仅限于*****科技开发有限公司内部使用,禁止用于其他的商业目的
*/
@Configuration
public class ThreadPoolConfig {
/**
*
* @Title: threadPoolTaskExecutor @Description: TODO
* 节点创建默认工作线程池。 @param: @return @return: Executor @throws
*/
@Bean(name = "threadPoolTaskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("threadpool-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
3、线程池功能测试:
package com.zzg.cron.component;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import com.zzg.cron.abstr.CronAbstract;
@Component("cronThreadPoolObject")
public class CronThreadPoolObject extends CronAbstract {
@Override
@Async(value = "threadPoolTaskExecutor")
public void execute() {
// TODO Auto-generated method stub
System.out.println("CronThreadPoolObject 对象执行输出任务:" + Thread.currentThread().getName());
}
}
注: 直接使用@Async注解,并声明线程池,即可使用多线程;