SpringBoot 集成线程池

符号 阅读:578 2021-03-31 20:58:06 评论:0

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注解,并声明线程池,即可使用多线程;

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号