怎么在java中利用注解實(shí)現(xiàn)一個(gè)可配置線程池

今天就跟大家聊聊有關(guān)怎么在java中利用注解實(shí)現(xiàn)一個(gè)可配置線程池,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比云龍網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式云龍網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋云龍地區(qū)。費(fèi)用合理售后完善,10余年實(shí)體公司更值得信賴。

Java的優(yōu)點(diǎn)是什么

1. 簡(jiǎn)單,只需理解基本的概念,就可以編寫適合于各種情況的應(yīng)用程序;2. 面向?qū)ο螅?. 分布性,Java是面向網(wǎng)絡(luò)的語言;4. 魯棒性,java提供自動(dòng)垃圾收集來進(jìn)行內(nèi)存管理,防止程序員在管理內(nèi)存時(shí)容易產(chǎn)生的錯(cuò)誤。;5. 安全性,用于網(wǎng)絡(luò)、分布環(huán)境下的Java必須防止病毒的入侵。6. 體系結(jié)構(gòu)中立,只要安裝了Java運(yùn)行時(shí)系統(tǒng),就可在任意處理器上運(yùn)行。7. 可移植性,Java可以方便地移植到網(wǎng)絡(luò)上的不同機(jī)器。8.解釋執(zhí)行,Java解釋器直接對(duì)Java字節(jié)碼進(jìn)行解釋執(zhí)行。

PoolConfig(線程池核心配置參數(shù)):

/**
 * <h2>線程池核心配置(<b >基本線程池?cái)?shù)量、最大線程池?cái)?shù)量、隊(duì)列初始容量、線程連接保持活動(dòng)秒數(shù)(默認(rèn)60s)</b>)</h2>
 * 
 * <blockquote><code>
 * <table border="1px"  width="100%"><tbody>
 * <tr><th >
 * 屬性名稱
 * </th><th >
 * 屬性含義
 * </th></tr>
 * <tr><td>
 * queueCapacity
 * </td><td>
 * 基本線程池?cái)?shù)量
 * </td></tr>
 * <tr><td>
 * count
 * </td><td>
 * 最大線程池?cái)?shù)量
 * </td></tr>
 * <tr><td>
 * maxCount
 * </td><td>
 * 隊(duì)列初始容量
 * </td></tr>
 * <tr><td>
 * aliveSec
 * </td><td>
 * 線程連接保持活動(dòng)秒數(shù)(默認(rèn)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配置項(xiàng)以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 >線程池核心配置、各個(gè)業(yè)務(wù)處理的任務(wù)數(shù)量</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>
 * 線程池各個(gè)業(yè)務(wù)任務(wù)初始的任務(wù)數(shù)
 * </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注解的任務(wù)集合:

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;
  } 
}

 線程執(zhí)行類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.因?yàn)槭褂玫膕pringboot項(xiàng)目,需要在application.properties 或者 application.yml 添加

#配置執(zhí)行的task線程數(shù)
thread.count.NeedExcutorTask=4
#最大存活時(shí)間
thread.pool.aliveSec=300000
#其他配置同理

2.將我們寫的線程配置進(jìn)行裝載到我們的項(xiàng)目中

@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("====== 任務(wù)執(zhí)行 =====")
  }
}

看完上述內(nèi)容,你們對(duì)怎么在java中利用注解實(shí)現(xiàn)一個(gè)可配置線程池有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

新聞標(biāo)題:怎么在java中利用注解實(shí)現(xiàn)一個(gè)可配置線程池
本文網(wǎng)址:http://muchs.cn/article28/gjgejp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信小程序、商城網(wǎng)站、品牌網(wǎng)站制作、外貿(mào)網(wǎng)站建設(shè)、服務(wù)器托管品牌網(wǎng)站設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司