温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在java中利用注解实现一个可配置线程池

发布时间:2021-05-07 17:04:42 来源:亿速云 阅读:112 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关怎么在java中利用注解实现一个可配置线程池,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

Java的优点是什么

1. 简单,只需理解基本的概念,就可以编写适合于各种情况的应用程序;2. 面向对象;3. 分布性,Java是面向网络的语言;4. 鲁棒性,java提供自动垃圾收集来进行内存管理,防止程序员在管理内存时容易产生的错误。;5. 安全性,用于网络、分布环境下的Java必须防止病毒的入侵。6. 体系结构中立,只要安装了Java运行时系统,就可在任意处理器上运行。7. 可移植性,Java可以方便地移植到网络上的不同机器。8.解释执行,Java解释器直接对Java字节码进行解释执行。

PoolConfig(线程池核心配置参数):

/**
 * <h2>线程池核心配置(<b >基本线程池数量、最大线程池数量、队列初始容量、线程连接保持活动秒数(默认60s)</b>)</h2>
 * 
 * <blockquote><code>
 * <table border="1px"  width="100%"><tbody>
 * <tr><th >
 * 属性名称
 * </th><th >
 * 属性含义
 * </th></tr>
 * <tr><td>
 * queueCapacity
 * </td><td>
 * 基本线程池数量
 * </td></tr>
 * <tr><td>
 * count
 * </td><td>
 * 最大线程池数量
 * </td></tr>
 * <tr><td>
 * maxCount
 * </td><td>
 * 队列初始容量
 * </td></tr>
 * <tr><td>
 * aliveSec
 * </td><td>
 * 线程连接保持活动秒数(默认60s)
 * </td></tr>
 * </tbody></table>
 * </code></blockquote>
 
 */
public class PoolConfig {
 
 private int queueCapacity = 200;
 
 private int count = 0;
 
 private int maxCount = 0;
 
 private int aliveSec;
 
 public int getQueueCapacity() {
 return queueCapacity;
 } 
 
 public void setQueueCapacity(int queueCapacity) {
 this.queueCapacity = queueCapacity;
 }
 
 public void setCount(int count) {
 this.count = count;
 }
 
 public void setMaxCount(int maxCount) {
 this.maxCount = maxCount;
 }
 
 public void setAliveSec(int aliveSec) {
 this.aliveSec = aliveSec;
 }
 
 public int getCount() {
 return count;
 }
 
 public int getMaxCount() {
 return maxCount;
 }
 
 public int getAliveSec() {
 return aliveSec;
 }
}

ThreadPoolConfig(线程池配置 yml配置项以thread开头):

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
 
/**
 * <h2>线程池配置(<b >线程池核心配置、各个业务处理的任务数量</b>)</h2>
 * 
 * <blockquote><code>
 * <table border="1px"  width="100%"><tbody>
 * <tr><th >
 * 属性名称
 * </th><th >
 * 属性含义
 * </th></tr>
 * <tr><td>
 * pool
 * </td><td>
 * 线程池核心配置
 * 【{@link PoolConfig}】
 * </td></tr>
 * <tr><td>
 * count
 * </td><td>
 * 线程池各个业务任务初始的任务数
 * </td></tr>
 * </tbody></table>
 * </code></blockquote>
 
 */
@Component
@ConfigurationProperties(prefix="thread")
public class ThreadPoolConfig {
 
 private PoolConfig pool = new PoolConfig();
 
 Map<String, Integer> count = new HashMap<>();
 
 public PoolConfig getPool() {
 return pool;
 }
 
 public void setPool(PoolConfig pool) {
 this.pool = pool;
 }
 
 public Map<String, Integer> getCount() {
 return count;
 }
 
}

定义Task注解,方便使用:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ExcutorTask {
 
 /**
 * The value may indicate a suggestion for a logical ExcutorTask name,
 * to be turned into a Spring bean in case of an autodetected ExcutorTask .
 * @return the suggested ExcutorTask name, if any
 */
 String value() default "";
 
}

通过反射获取使用Task注解的任务集合:

public class Beans {
 
 private static final char PREFIX = '.';
 
 public static ConcurrentMap<String, String> scanBeanClassNames(){
 ConcurrentMap<String, String> beanClassNames = new ConcurrentHashMap<>();
 ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); 
   provider.addIncludeFilter(new AnnotationTypeFilter(ExcutorTask.class));
   for(Package pkg : Package.getPackages()){
   String basePackage = pkg.getName();
     Set<BeanDefinition> components = provider.findCandidateComponents(basePackage); 
     for (BeanDefinition component : components) {
     String beanClassName = component.getBeanClassName();
     try {
    Class<?> clazz = Class.forName(component.getBeanClassName());
    boolean isAnnotationPresent = clazz.isAnnotationPresent(ZimaTask.class);
    if(isAnnotationPresent){
     ZimaTask task = clazz.getAnnotation(ExcutorTask.class);
     String aliasName = task.value();
     if(aliasName != null && !"".equals(aliasName)){
     beanClassNames.put(aliasName, component.getBeanClassName());
     }
    }
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
     beanClassNames.put(beanClassName.substring(beanClassName.lastIndexOf(PREFIX) + 1), component.getBeanClassName());
     }
   }
   return beanClassNames;
  } 
}

 线程执行类TaskPool:

@Component
public class TaskPool {
 
 public ThreadPoolTaskExecutor poolTaskExecutor;
 
 @Autowired 
 private ThreadPoolConfig threadPoolConfig;
 
 @Autowired 
 private ApplicationContext context;
 
 private final Integer MAX_POOL_SIZE = 2000;
 
 private PoolConfig poolCfg;
 
 private Map<String, Integer> tasksCount;
 
 private ConcurrentMap<String, String> beanClassNames;
 
 @PostConstruct
  public void init() {
 
 beanClassNames = Beans.scanBeanClassNames();
   
   poolTaskExecutor = new ThreadPoolTaskExecutor();
   
   poolCfg = threadPoolConfig.getPool();
 
 tasksCount = threadPoolConfig.getCount();
 
 int corePoolSize = poolCfg.getCount(), 
  maxPoolSize = poolCfg.getMaxCount(), 
  queueCapacity = poolCfg.getQueueCapacity(), 
  minPoolSize = 0, maxCount = (corePoolSize << 1);
 
 for(String taskName : tasksCount.keySet()){
  minPoolSize += tasksCount.get(taskName);
 }
 
 if(corePoolSize > 0){
  if(corePoolSize <= minPoolSize){
  corePoolSize = minPoolSize;
  }
 }else{
  corePoolSize = minPoolSize;
 }
 
 if(queueCapacity > 0){
  poolTaskExecutor.setQueueCapacity(queueCapacity);
 }
 
 if(corePoolSize > 0){
  if(MAX_POOL_SIZE < corePoolSize){
  corePoolSize = MAX_POOL_SIZE;
  }
  poolTaskExecutor.setCorePoolSize(corePoolSize);
 }
 
 if(maxPoolSize > 0){
  if(maxPoolSize <= maxCount){
  maxPoolSize = maxCount;
  }
  if(MAX_POOL_SIZE < maxPoolSize){
  maxPoolSize = MAX_POOL_SIZE;
  }
  poolTaskExecutor.setMaxPoolSize(maxPoolSize);
 }
 
 if(poolCfg.getAliveSec() > 0){
  poolTaskExecutor.setKeepAliveSeconds(poolCfg.getAliveSec());
 }
 
 poolTaskExecutor.initialize();
  }
  
 public void execute(Class<?>... clazz){
 int i = 0, len = tasksCount.size();
 for(; i < len; i++){
  Integer taskCount = tasksCount.get(i);
  for(int t = 0; t < taskCount; t++){
  try{
   Object taskObj = context.getBean(clazz[i]);
   if(taskObj != null){
   poolTaskExecutor.execute((Runnable) taskObj);
   }
  }catch(Exception ex){
   ex.printStackTrace();
  }
  }
 }
  }
  
 public void execute(String... args){
   int i = 0, len = tasksCount.size();
 for(; i < len; i++){
  Integer taskCount = tasksCount.get(i);
  for(int t = 0; t < taskCount; t++){
  try{
   Object taskObj = null;
   if(context.containsBean(args[i])){
   taskObj = context.getBean(args[i]);
   }else{
   if(beanClassNames.containsKey(args[i].toLowerCase())){
    Class<?> clazz = Class.forName(beanClassNames.get(args[i].toLowerCase()));
    taskObj = context.getBean(clazz);
   }
   }
   if(taskObj != null){
   poolTaskExecutor.execute((Runnable) taskObj);
   }
  }catch(Exception ex){
   ex.printStackTrace();
  }
  }
 }
  }
 
 public void execute(){
 for(String taskName : tasksCount.keySet()){
  Integer taskCount = tasksCount.get(taskName);
  for(int t = 0; t < taskCount; t++){
  try{
   Object taskObj = null;
   if(context.containsBean(taskName)){
   taskObj = context.getBean(taskName);
   }else{
   if(beanClassNames.containsKey(taskName)){
    Class<?> clazz = Class.forName(beanClassNames.get(taskName));
    taskObj = context.getBean(clazz);
   }
   }
   if(taskObj != null){
   poolTaskExecutor.execute((Runnable) taskObj);
   }
  }catch(Exception ex){
   ex.printStackTrace();
  }
  }
 }
  }
  
}

如何使用?(做事就要做全套 ^_^)

1.因为使用的springboot项目,需要在application.properties 或者 application.yml 添加

#配置执行的task线程数
thread.count.NeedExcutorTask=4
#最大存活时间
thread.pool.aliveSec=300000
#其他配置同理

2.将我们写的线程配置进行装载到我们的项目中

@Configuration
public class TaskManager {
 
 @Resource
 private TaskPool taskPool;
 
 @PostConstruct
 public void executor(){
 taskPool.execute();
 }
}

3.具体使用

@ExcutorTask
public class NeedExcutorTask implements Runnable{
  @Override
 public void run() {
    Thread.sleep(1000L);
    log.info("====== 任务执行 =====")
  }
}

看完上述内容,你们对怎么在java中利用注解实现一个可配置线程池有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI