最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java 注解實(shí)現(xiàn)一個(gè)可配置線程池的方法示例

 更新時(shí)間:2019年01月30日 10:44:19   作者:Go Big Or Go Home  
這篇文章主要介紹了java 注解實(shí)現(xiàn)一個(gè)可配置線程池的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

前言

項(xiàng)目需要多線程執(zhí)行一些Task,為了方便各個(gè)服務(wù)的使用。特意封裝了一個(gè)公共工具類,下面直接擼代碼:

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

/**
 * <h1>線程池核心配置(<b style="color:#CD0000">基本線程池?cái)?shù)量、最大線程池?cái)?shù)量、隊(duì)列初始容量、線程連接保持活動(dòng)秒數(shù)(默認(rèn)60s)</b>)</h1>
 * 
 * <blockquote><code>
 * <table border="1px" style="border-color:gray;" width="100%"><tbody>
 * <tr><th style="color:green;text-align:left;">
 * 屬性名稱
 * </th><th style="color:green;text-align:left;">
 * 屬性含義
 * </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;
 
/**
 * <h1>線程池配置(<b style="color:#CD0000">線程池核心配置、各個(gè)業(yè)務(wù)處理的任務(wù)數(shù)量</b>)</h1>
 * 
 * <blockquote><code>
 * <table border="1px" style="border-color:gray;" width="100%"><tbody>
 * <tr><th style="color:green;text-align:left;">
 * 屬性名稱
 * </th><th style="color:green;text-align:left;">
 * 屬性含義
 * </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í)行 =====")
  }
}

以上就是創(chuàng)建一個(gè)可擴(kuò)展的線程池相關(guān)的配置(望指教~~~)。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • spring security4 添加驗(yàn)證碼的示例代碼

    spring security4 添加驗(yàn)證碼的示例代碼

    本篇文章主要介紹了spring security4 添加驗(yàn)證碼的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-02-02
  • IDEA maven引入SSL證書校驗(yàn)問題及處理

    IDEA maven引入SSL證書校驗(yàn)問題及處理

    這篇文章主要討論了在Maven項(xiàng)目中遇到依賴導(dǎo)入問題,特別是關(guān)于PKIX路徑構(gòu)建失敗的錯(cuò)誤,文章提供了三種解決方法:手動(dòng)下載依賴、忽略SSL證書校驗(yàn)以及生成并導(dǎo)入SSL證書,每種方法都有詳細(xì)的步驟和示例代碼,幫助開發(fā)者解決這個(gè)問題
    2025-02-02
  • Java面試之線程通訊方式詳解

    Java面試之線程通訊方式詳解

    線程通信是指多個(gè)線程之間通過某種機(jī)制進(jìn)行協(xié)調(diào)和交互,那為什么一個(gè)線程等待和通知機(jī)制就需要這么多的實(shí)現(xiàn)方式呢?別著急,下面小編來和大家仔細(xì)聊聊
    2023-08-08
  • java實(shí)現(xiàn)單詞查詢小程序

    java實(shí)現(xiàn)單詞查詢小程序

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)單詞查詢小程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-07-07
  • springdoc?openapi使用解決方案

    springdoc?openapi使用解決方案

    SpringDoc注解的使用,它是基于OpenAPI?3和Swagger?3的現(xiàn)代化解決方案,相較于舊版的Swagger2即SpringFox,SpringDoc提供了更簡潔、更直觀的注解方式,這篇文章主要介紹了springdoc?openapi使用,需要的朋友可以參考下
    2024-04-04
  • 解析Java程序中對(duì)象內(nèi)存的分配和控制的基本方法

    解析Java程序中對(duì)象內(nèi)存的分配和控制的基本方法

    這篇文章主要介紹了解析Java程序中對(duì)象內(nèi)存的分配和控制的基本方法,包括計(jì)算對(duì)象的內(nèi)存占用的方法,要的朋友可以參考下
    2016-04-04
  • Java8需要知道的4個(gè)函數(shù)式接口簡單教程

    Java8需要知道的4個(gè)函數(shù)式接口簡單教程

    這篇文章主要介紹了Java?8中引入的函數(shù)式接口,包括Consumer、Supplier、Predicate和Function,以及它們的用法和特點(diǎn),文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2025-03-03
  • 詳解Java多線程與并發(fā)

    詳解Java多線程與并發(fā)

    多線程是一個(gè)進(jìn)程在執(zhí)行過程中產(chǎn)生多個(gè)更小的程序單元,這些更小的單元稱為線程,這些線程可以同時(shí)存在,同時(shí)運(yùn)行,一個(gè)進(jìn)程可能包含多個(gè)同時(shí)執(zhí)行的線程。多線程是實(shí)現(xiàn)并發(fā)機(jī)制的一種有效手段。進(jìn)程和線程一樣,都是實(shí)現(xiàn)并發(fā)的一個(gè)基本單位。
    2021-06-06
  • Java webSerivce的使用看完你就明白了

    Java webSerivce的使用看完你就明白了

    因?yàn)榍岸螘r(shí)間,需要使用到webService來調(diào)用公司的其他系統(tǒng)api接口,但是請(qǐng)求方式和我熟知的http請(qǐng)求不一樣,是基于soap協(xié)議來傳輸xml數(shù)據(jù)格式,請(qǐng)求的參數(shù)極其復(fù)雜,需要封裝多層xml數(shù)據(jù)格式,并且我不知道對(duì)方的api接口是什么語言,甚至不知道他們存在于什么平臺(tái)
    2022-03-03
  • SpringBoot如何集成Token

    SpringBoot如何集成Token

    文章介紹了如何使用jjwt插件實(shí)現(xiàn)Token的生成和校驗(yàn),該插件可以直接與SpringBoot集成,Token由三部分組成,分別是header、payload和signature,通過在請(qǐng)求頭中傳遞Token,后端可以驗(yàn)證其合法性,從而提高安全性
    2025-01-01

最新評(píng)論

安丘市| 宜宾市| 房产| 于田县| 岳西县| 阳高县| 慈溪市| 新巴尔虎右旗| 南阳市| 雷州市| 花莲市| 德阳市| SHOW| 徐水县| 宜丰县| 东源县| 江永县| 习水县| 安西县| 平顺县| 平山县| 长治市| 商洛市| 怀来县| 巴林左旗| 建平县| 安溪县| 洞头县| 涿鹿县| 潼南县| 和平县| 阿城市| 衡水市| 靖西县| 曲阜市| 正蓝旗| 安宁市| 冷水江市| 安陆市| 德化县| 永胜县|