Jelajahi Sumber

线程池访问更新

wangliang 9 bulan lalu
induk
melakukan
39f8a6f80d

+ 1 - 1
distributed-print-business/src/main/java/com/qmth/distributed/print/business/templete/create/AsyncCreateTaskTemplete.java

@@ -23,7 +23,7 @@ public abstract class AsyncCreateTaskTemplete extends AsyncImportTaskTemplete {
     /**
      * 创建pdf
      */
-//    @Async("taskThreadPool")
+    @Async("taskThreadPool")
     public Result createPdf(TBTaskPdf tbTaskPdf, CallbackCreatePdf callbackCreatePdf) {
         return null;
     }

+ 176 - 4
distributed-print/src/main/java/com/qmth/distributed/print/api/obe/TRBasicInfoController.java

@@ -1,5 +1,6 @@
 package com.qmth.distributed.print.api.obe;
 
+import cn.hutool.core.date.DateUtil;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@@ -46,6 +47,7 @@ import com.qmth.teachcloud.obe.service.*;
 import io.swagger.annotations.*;
 import org.apache.commons.collections4.CollectionUtils;
 import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
 import org.apache.poi.ss.usermodel.*;
 import org.apache.poi.ss.util.CellRangeAddress;
 import org.apache.poi.ss.util.RegionUtil;
@@ -62,11 +64,15 @@ import javax.annotation.Resource;
 import javax.validation.Valid;
 import javax.validation.constraints.Max;
 import javax.validation.constraints.Min;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
+import java.io.*;
 import java.math.BigDecimal;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.text.MessageFormat;
 import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.stream.Collectors;
 
@@ -711,7 +717,7 @@ public class TRBasicInfoController {
     public Result wordTopdfTest() throws Exception {
         if (customRedisLockProvider.tryLock(LockType.CREATE_PDF, "1")) {
             try {
-                if (!customRedisLockProvider.isLocked(LockType.CREATE_PDF, "1")) {
+                if (!customRedisLockProvider.isWriteLocked(LockType.CREATE_PDF, "1")) {
                     customRedisLockProvider.waitLock(LockType.CREATE_PDF, "1");
                 }
                 customRedisLockProvider.watch(LockType.CREATE_PDF, "1");
@@ -728,4 +734,170 @@ public class TRBasicInfoController {
         }
         return ResultUtil.ok(true);
     }
+
+    public static boolean threadBreak = false;
+    public static CopyOnWriteArrayList<Integer> threadKeyList = new CopyOnWriteArrayList<>();
+    public static String path = "/Users/king/Downloads/";
+    public static File fileDir = new File(path + "thread_test");
+    public static final String lockName = ":txt:file";
+    public static final String one = "[一]";
+    public static final String two = "[二]";
+    public static ConcurrentHashMap<Integer, Integer> keyMap = new ConcurrentHashMap<>();
+
+    @ApiOperation(value = "线程测试")
+    @RequestMapping(value = "/thread/test", method = RequestMethod.POST)
+    @ApiResponses({@ApiResponse(code = 200, message = "测试成功", response = Object.class)})
+    @Aac(auth = false)
+    public Result threadTest() throws IOException, Exception {
+        threadBreak = false;
+        AtomicInteger threadReleaseToatlCount = new AtomicInteger(0);
+        threadKeyList.clear();
+        keyMap.clear();
+        int num = 100;
+        for (; ; ) {
+            int key = new Random().nextInt(num) + 1;
+            if (!keyMap.containsKey(key)) {
+                keyMap.put(key, key);
+                new Thread(() -> {
+                    //开始尝试获取锁
+                    if (customRedisLockProvider.tryLock(LockType.CREATE_PDF, key + "", 1L, TimeUnit.DAYS)) {
+                        log.info("########线程key:{}已获得锁########", key);
+                        try {
+                            StringJoiner stringJoinerSummary = this.readTxtFile(key + "");
+                            this.writeTxtFile(stringJoinerSummary, key + "", one + "->线程key:" + key + "已获得锁");
+                        } catch (IOException | InterruptedException e) {
+                            e.printStackTrace();
+                        }
+                        try {
+                            threadKeyList.add(key);
+                            long i = 0;
+                            do {
+                                i = i + new Random().nextInt(100) + 1;
+                                if ((Thread.currentThread().getId() & 1) == 0) {
+                                    Thread.sleep(new Random().nextInt(100) + 1);
+                                } else {
+                                    Thread.sleep(new Random().nextInt(50) + 1);
+                                }
+                            } while (i < 100000);
+                        } catch (InterruptedException e) {
+                            e.printStackTrace();
+                        } finally {
+                            customRedisLockProvider.unlock(LockType.CREATE_PDF, key + "");
+                            threadReleaseToatlCount.incrementAndGet();
+                            log.info("########线程key:{}已被释放,总计:{}########", key, threadReleaseToatlCount.get());
+                            try {
+                                StringJoiner stringJoinerSummary = this.readTxtFile(key + "");
+                                this.writeTxtFile(stringJoinerSummary, key + "", one + "->线程key:" + key + "已被释放");
+                            } catch (InterruptedException | IOException e) {
+                                e.printStackTrace();
+                            }
+                            if (threadReleaseToatlCount.get() == num) {
+                                threadBreak = true;
+                            }
+                        }
+                    }
+                }).start();
+            }
+            Thread.sleep(1000);
+            if (keyMap.size() == num) {
+                log.info("########线程生成完毕########");
+                break;
+            }
+        }
+        return ResultUtil.ok(true);
+    }
+
+    @ApiOperation(value = "线程抢夺测试")
+    @RequestMapping(value = "/thread/reave/test", method = RequestMethod.POST)
+    @ApiResponses({@ApiResponse(code = 200, message = "测试成功", response = Object.class)})
+    @Aac(auth = false)
+    public Result threadReaveTest() throws IOException, Exception {
+        AtomicInteger threadReaveToatlCount = new AtomicInteger(0);
+        //开始尝试获取锁
+        for (; ; ) {
+            int index = new Random().nextInt(threadKeyList.size());
+            int key = threadKeyList.get(index);
+            if (customRedisLockProvider.tryLock(LockType.CREATE_PDF, key + "")) {
+                log.info("%%%%%%%%%线程key:{}抢到锁%%%%%%%%%", key);
+                StringJoiner stringJoinerSummary = this.readTxtFile(key + "");
+                this.writeTxtFile(stringJoinerSummary, key + "", two + "->线程key:" + key + "抢到锁");
+                threadReaveToatlCount.incrementAndGet();
+                threadKeyList.remove(key);
+                customRedisLockProvider.unlock(LockType.CREATE_PDF, key + "");
+            } else {
+                log.info("%%%%%%%%%线程key:{}正被锁定%%%%%%%%%", key);
+                StringJoiner stringJoinerSummary = this.readTxtFile(key + "");
+                this.writeTxtFile(stringJoinerSummary, key + "", two + "->线程key:" + key + "正被锁定");
+            }
+            Thread.sleep(1000);
+            if (threadKeyList.size() == 0 || threadBreak) {
+                log.info("%%%%%%%%%线程抢夺完毕%%%%%%%%%,总计:{}", threadReaveToatlCount.get());
+                break;
+            }
+        }
+        return ResultUtil.ok(true);
+    }
+
+    /**
+     * 获取txt文件读锁
+     *
+     * @param key
+     * @return
+     * @throws IOException
+     */
+    protected StringJoiner readTxtFile(String key) throws IOException {
+        if (!fileDir.exists()) {
+            fileDir.mkdirs();
+        }
+        File file = new File(fileDir.getPath() + File.separator + key + ".txt");
+        if (!file.exists()) {
+            file.createNewFile();
+        }
+        StringJoiner stringJoinerSummary = new StringJoiner("\n");
+        try {
+            customRedisLockProvider.watch(LockType.CREATE_PDF, key + lockName + ":read");
+            String text = IOUtils.toString(new FileInputStream(file), Charset.forName(SystemConstant.CHARSET_NAME));
+            if (Objects.nonNull(text) && !Objects.equals(text.trim(), "")) {
+                stringJoinerSummary.add(text);
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            customRedisLockProvider.unwatch(LockType.CREATE_PDF, key + lockName + ":read");
+        }
+        return stringJoinerSummary;
+    }
+
+    /**
+     * txt文件写锁
+     *
+     * @param stringJoinerSummary
+     * @param key
+     * @param message
+     * @throws InterruptedException
+     */
+    protected void writeTxtFile(StringJoiner stringJoinerSummary, String key, String message) throws InterruptedException, IOException {
+        if (!fileDir.exists()) {
+            fileDir.mkdirs();
+        }
+        File file = new File(fileDir.getPath() + File.separator + key + ".txt");
+        if (!file.exists()) {
+            file.createNewFile();
+        }
+        for (; ; ) {
+            if (!customRedisLockProvider.isWriteLocked(LockType.CREATE_PDF, key + lockName + ":wirte")) {
+                try {
+                    customRedisLockProvider.waitLock(LockType.CREATE_PDF, key + lockName + ":wirte");
+                    stringJoinerSummary.add(MessageFormat.format("{0}{1}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), message));
+                    IOUtils.write(stringJoinerSummary.toString().getBytes(StandardCharsets.UTF_8), new FileOutputStream(file));
+                } catch (IOException e) {
+                    e.printStackTrace();
+                } finally {
+                    customRedisLockProvider.unlock(LockType.CREATE_PDF, key + lockName + ":wirte");
+                    break;
+                }
+            }
+            Thread.sleep(500);
+        }
+    }
 }

+ 2 - 0
teachcloud-common/src/main/java/com/qmth/teachcloud/common/contant/SystemConstant.java

@@ -557,6 +557,8 @@ public class SystemConstant {
     public static final long REDIS_LOCK_OBE_RADAR_DATA_TIME_OUT = 60L * 10;
     public static final long REDIS_COURSE_DEGREE_DATA_TIME_OUT = 60L * 10;
     public static final long REDIS_LOCK_DEFAULT_TIME_OUT = 60L * 2;//请求超时
+    public static final long REDIS_LOCK_GET_DEFAULT_TIME_OUT = 30L;//默认30秒
+
     /**
      * 机器心跳
      */

+ 5 - 1
teachcloud-common/src/main/java/com/qmth/teachcloud/common/threadPool/MyThreadPool.java

@@ -53,7 +53,7 @@ public class MyThreadPool extends ThreadPoolTaskExecutor {
             log.info("cpuNum:{}", cpuNum);
             threadPoolTaskExecutor = new MyThreadPool();
             if (!customThreadPoolCoreSize && cpuNum > 0) {
-                threadPoolTaskExecutor.setCorePoolSize(Math.abs(cpuNum / 2));//核心线程数
+                threadPoolTaskExecutor.setCorePoolSize(Math.abs(cpuNum));//核心线程数
                 threadPoolTaskExecutor.setMaxPoolSize(threadPoolTaskExecutor.getCorePoolSize() * 2);//最大线程数
             } else {
                 threadPoolTaskExecutor.setCorePoolSize(threadPoolCoreSize);//核心线程数
@@ -72,4 +72,8 @@ public class MyThreadPool extends ThreadPoolTaskExecutor {
         }
         return threadPoolTaskExecutor;
     }
+
+    public MyThreadPool getThreadPoolTaskExecutor() {
+        return threadPoolTaskExecutor;
+    }
 }

+ 30 - 0
teachcloud-mark/src/main/java/com/qmth/teachcloud/mark/lock/RedisLockProvider.java

@@ -0,0 +1,30 @@
+package com.qmth.teachcloud.mark.lock;
+
+import com.qmth.teachcloud.mark.enums.LockType;
+
+import java.util.concurrent.TimeUnit;
+
+public interface RedisLockProvider {
+
+    void waitLock(LockType type, String key);
+
+    void waitLock(LockType type, String key, Long time, TimeUnit timeUnit);
+
+    boolean tryLock(LockType type, String key);
+
+    boolean tryLock(LockType type, String key, Long time, TimeUnit timeUnit);
+
+    void unlock(LockType type, String key);
+
+    boolean isWriteLocked(LockType type, String key);
+
+    boolean isReadLocked(LockType type, String key);
+
+    void watch(LockType type, String key);
+
+    void watch(LockType type, String key, Long time, TimeUnit timeUnit);
+
+    void unwatch(LockType type, String key);
+
+    void clear();
+}

+ 73 - 6
teachcloud-mark/src/main/java/com/qmth/teachcloud/mark/lock/impl/CustomRedisLockProvider.java

@@ -1,11 +1,14 @@
 package com.qmth.teachcloud.mark.lock.impl;
 
 import com.qmth.teachcloud.common.contant.SystemConstant;
+import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
 import com.qmth.teachcloud.common.util.RedisUtil;
 import com.qmth.teachcloud.mark.enums.LockType;
-import com.qmth.teachcloud.mark.lock.LockProvider;
+import com.qmth.teachcloud.mark.lock.RedisLockProvider;
 import org.redisson.api.RReadWriteLock;
 import org.redisson.api.RedissonClient;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
 import org.springframework.util.CollectionUtils;
 
@@ -19,7 +22,8 @@ import java.util.concurrent.TimeUnit;
  * @author luoshi
  */
 @Component("customRedisLockProvider")
-public class CustomRedisLockProvider implements LockProvider {
+public class CustomRedisLockProvider implements RedisLockProvider {
+    private final static Logger log = LoggerFactory.getLogger(CustomRedisLockProvider.class);
 
     @Resource
     RedisUtil redisUtil;
@@ -29,13 +33,40 @@ public class CustomRedisLockProvider implements LockProvider {
 
     @Override
     public void waitLock(LockType type, String key) {
-        getLock(type, key).writeLock().lock(SystemConstant.REDIS_LOCK_DEFAULT_TIME_OUT, TimeUnit.SECONDS);
+        if (!this.isWriteLocked(type, key) && !this.isReadLocked(type, key)) {
+            getLock(type, key).writeLock().lock(SystemConstant.REDIS_LOCK_DEFAULT_TIME_OUT, TimeUnit.SECONDS);
+            log.info(">>>>>>>类型:{},key:{},写锁上锁成功,锁时长:{}", type.name(), key, SystemConstant.REDIS_LOCK_DEFAULT_TIME_OUT);
+        } else {
+            if (this.isReadLocked(type, key)) {
+                throw ExceptionResultEnum.ERROR.exception("获取写锁失败,请先释放读锁");
+            } else if (this.isWriteLocked(type, key)) {
+                throw ExceptionResultEnum.ERROR.exception("获取写锁失败,已获取到锁无需重复获取");
+            }
+        }
+    }
+
+    @Override
+    public void waitLock(LockType type, String key, Long time, TimeUnit timeUnit) {
+        if (!this.isWriteLocked(type, key) && !this.isReadLocked(type, key)) {
+            getLock(type, key).writeLock().lock(time, timeUnit);
+            log.info(">>>>>>>类型:{},key:{},写锁上锁成功,锁时长:{}", type.name(), key, time + "|" + timeUnit);
+        } else {
+            if (this.isReadLocked(type, key)) {
+                throw ExceptionResultEnum.ERROR.exception("获取写锁失败,请先释放读锁");
+            } else if (this.isWriteLocked(type, key)) {
+                throw ExceptionResultEnum.ERROR.exception("获取写锁失败,已获取到锁无需重复获取");
+            }
+        }
     }
 
     @Override
     public boolean tryLock(LockType type, String key) {
         try {
-            return getLock(type, key).writeLock().tryLock(30L, SystemConstant.REDIS_LOCK_DEFAULT_TIME_OUT, TimeUnit.SECONDS);
+            if (!this.isWriteLocked(type, key)) {
+                boolean lock = getLock(type, key).writeLock().tryLock(SystemConstant.REDIS_LOCK_GET_DEFAULT_TIME_OUT, SystemConstant.REDIS_LOCK_DEFAULT_TIME_OUT, TimeUnit.SECONDS);
+                log.info(">>>>>>>类型:{},key:{},写锁尝试上锁成功,锁时长:{}", type.name(), key, SystemConstant.REDIS_LOCK_GET_DEFAULT_TIME_OUT);
+                return lock;
+            }
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
@@ -43,23 +74,59 @@ public class CustomRedisLockProvider implements LockProvider {
     }
 
     @Override
-    public boolean isLocked(LockType type, String key) {
-        return getLock(type, key).writeLock().isLocked();
+    public boolean tryLock(LockType type, String key, Long time, TimeUnit timeUnit) {
+        try {
+            if (!this.isWriteLocked(type, key)) {
+                boolean lock = getLock(type, key).writeLock().tryLock(SystemConstant.REDIS_LOCK_GET_DEFAULT_TIME_OUT, time, timeUnit);
+                log.info(">>>>>>>类型:{},key:{},写锁尝试上锁成功,锁时长:{}", type.name(), key, time + "|" + timeUnit);
+                return lock;
+            }
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+
+    @Override
+    public boolean isWriteLocked(LockType type, String key) {
+        boolean lock = getLock(type, key).writeLock().isLocked();
+        log.info(">>>>>>>类型:{},key:{},写锁是否上锁:{}", type.name(), key, lock);
+        return lock;
+    }
+
+    @Override
+    public boolean isReadLocked(LockType type, String key) {
+        boolean lock = getLock(type, key).readLock().isLocked();
+        log.info(">>>>>>>类型:{},key:{},读锁是否上锁:{}", type.name(), key, lock);
+        return lock;
     }
 
     @Override
     public void unlock(LockType type, String key) {
         getLock(type, key).writeLock().unlock();
+        log.info(">>>>>>>类型:{},key:{},写锁释放锁成功", type.name(), key);
     }
 
     @Override
     public void watch(LockType type, String key) {
+//        if (!this.isReadLocked(type, key)) {
         getLock(type, key).readLock().lock(SystemConstant.REDIS_LOCK_DEFAULT_TIME_OUT, TimeUnit.SECONDS);
+        log.info(">>>>>>>类型:{},key:{},读锁上锁成功,锁时长:{}", type.name(), key, SystemConstant.REDIS_LOCK_GET_DEFAULT_TIME_OUT);
+//        }
+    }
+
+    @Override
+    public void watch(LockType type, String key, Long time, TimeUnit timeUnit) {
+//        if (!this.isReadLocked(type, key)) {
+        getLock(type, key).readLock().lock(time, timeUnit);
+        log.info(">>>>>>>类型:{},key:{},读锁上锁成功,锁时长:{}", type.name(), key, time + "|" + timeUnit);
+//        }
     }
 
     @Override
     public void unwatch(LockType type, String key) {
         getLock(type, key).readLock().unlock();
+        log.info(">>>>>>>类型:{},key:{},读锁释放锁成功", type.name(), key);
     }
 
     private RReadWriteLock getLock(LockType type, String key) {

+ 1 - 4
teachcloud-task/src/main/java/com/qmth/teachcloud/task/job/service/JobService.java

@@ -1,8 +1,5 @@
 package com.qmth.teachcloud.task.job.service;
 
-import java.io.IOException;
-import java.util.concurrent.ExecutionException;
-
 /**
  * @Description: job service
  * @Param:
@@ -53,5 +50,5 @@ public interface JobService {
 
     void clearTimeoutTask();
 
-    void createPdfTask() throws ExecutionException, InterruptedException;
+    void createPdfTask();
 }

+ 34 - 64
teachcloud-task/src/main/java/com/qmth/teachcloud/task/job/service/impl/JobServiceImpl.java

@@ -12,14 +12,12 @@ import com.qmth.teachcloud.common.bean.dto.MqDto;
 import com.qmth.teachcloud.common.bean.vo.PaperInfoVo;
 import com.qmth.teachcloud.common.contant.SystemConstant;
 import com.qmth.teachcloud.common.entity.BasicCourse;
-import com.qmth.teachcloud.common.entity.SysConfig;
-import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
 import com.qmth.teachcloud.common.enums.PushTypeEnum;
 import com.qmth.teachcloud.common.enums.TaskResultEnum;
 import com.qmth.teachcloud.common.enums.TaskStatusEnum;
 import com.qmth.teachcloud.common.enums.mark.MarkPaperStatus;
 import com.qmth.teachcloud.common.service.BasicCourseService;
-import com.qmth.teachcloud.common.service.CommonCacheService;
+import com.qmth.teachcloud.common.threadPool.MyThreadPool;
 import com.qmth.teachcloud.common.util.DateDisposeUtils;
 import com.qmth.teachcloud.common.util.ExamTaskUtil;
 import com.qmth.teachcloud.common.util.RedisUtil;
@@ -35,19 +33,15 @@ import com.qmth.teachcloud.mark.service.MarkUserGroupService;
 import com.qmth.teachcloud.mark.utils.TaskLockUtil;
 import com.qmth.teachcloud.task.job.service.JobService;
 import com.qmth.teachcloud.task.service.PrintFinishService;
-import org.apache.commons.collections4.CollectionUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 import org.springframework.stereotype.Service;
 
 import javax.annotation.Resource;
+import java.math.BigDecimal;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
-import java.util.Optional;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -94,6 +88,9 @@ public class JobServiceImpl implements JobService {
     @Resource
     LockService lockService;
 
+    @Resource
+    MyThreadPool myThreadPool;
+
     @Override
     public void sendSmsExpireTask() {
         smsSendService.sendSmsExpireTask();
@@ -208,31 +205,41 @@ public class JobServiceImpl implements JobService {
         }
     }
 
-    @Resource
-    CommonCacheService commonCacheService;
-
     @Override
-    public void createPdfTask() throws ExecutionException, InterruptedException {
-        List<TBTaskPdf> tbTaskPdfList = tbTaskPdfService.listWaitingTask();
-        if (CollectionUtils.isNotEmpty(tbTaskPdfList)) {
-            ThreadPoolTaskExecutor threadPoolTaskExecutor = this.createThreadPool();
-            log.info("ThreadPoolTaskExecutor线程池准备开始创建PDF");
+    public void createPdfTask() {
+        if (this.getMyThreadPoolPercent()) {
+            List<TBTaskPdf> tbTaskPdfList = tbTaskPdfService.listWaitingTask();
             for (TBTaskPdf tbTaskPdf : tbTaskPdfList) {
-                threadPoolTaskExecutor.execute(new Thread(() -> asyncCreatePdfTemplateService.createPdf(tbTaskPdf, null)));
+                if (this.getMyThreadPoolPercent()) {
+                    log.info("ThreadPoolTaskExecutor 执行线程");
+                    asyncCreatePdfTemplateService.createPdf(tbTaskPdf, null);
+                } else {
+                    log.info("ThreadPoolTaskExecutor 不执行线程");
+                    break;
+                }
             }
-            log.info("ThreadPoolTaskExecutor corePoolSize:{},maximumPoolSize:{},poolSize:{},queueSize:{},activeCount:{},completedTaskCount:{},taskCount:{}",
-                    threadPoolTaskExecutor.getThreadPoolExecutor().getCorePoolSize(),
-                    threadPoolTaskExecutor.getThreadPoolExecutor().getMaximumPoolSize(),
-                    threadPoolTaskExecutor.getThreadPoolExecutor().getPoolSize(),
-                    threadPoolTaskExecutor.getThreadPoolExecutor().getQueue().size(),
-                    threadPoolTaskExecutor.getThreadPoolExecutor().getActiveCount(),
-                    threadPoolTaskExecutor.getThreadPoolExecutor().getCompletedTaskCount(),
-                    threadPoolTaskExecutor.getThreadPoolExecutor().getTaskCount());
-            threadPoolTaskExecutor.shutdown();
-            log.info("ThreadPoolTaskExecutor线程池已关闭");
         }
     }
 
+    /**
+     * 获取线程使用率
+     *
+     * @return
+     */
+    protected Boolean getMyThreadPoolPercent() {
+        int rate = myThreadPool.getThreadPoolTaskExecutor().getThreadPoolExecutor().getQueue().size() + myThreadPool.getThreadPoolTaskExecutor().getThreadPoolExecutor().getActiveCount();
+        BigDecimal percent = new BigDecimal(rate).divide(new BigDecimal(myThreadPool.getThreadPoolTaskExecutor().getThreadPoolExecutor().getMaximumPoolSize()), 2, BigDecimal.ROUND_HALF_UP).multiply(SystemConstant.PERCENT).setScale(2, BigDecimal.ROUND_HALF_UP);
+        log.info("ThreadPoolTaskExecutor percent:{},corePoolSize:{},maximumPoolSize:{},poolSize:{},queueSize:{},activeCount:{},completedTaskCount:{},taskCount:{}", percent,
+                myThreadPool.getThreadPoolTaskExecutor().getThreadPoolExecutor().getCorePoolSize(),
+                myThreadPool.getThreadPoolTaskExecutor().getThreadPoolExecutor().getMaximumPoolSize(),
+                myThreadPool.getThreadPoolTaskExecutor().getThreadPoolExecutor().getPoolSize(),
+                myThreadPool.getThreadPoolTaskExecutor().getThreadPoolExecutor().getQueue().size(),
+                myThreadPool.getThreadPoolTaskExecutor().getThreadPoolExecutor().getActiveCount(),
+                myThreadPool.getThreadPoolTaskExecutor().getThreadPoolExecutor().getCompletedTaskCount(),
+                myThreadPool.getThreadPoolTaskExecutor().getThreadPoolExecutor().getTaskCount());
+        return percent.compareTo(SystemConstant.PERCENT) == -1 ? true : false;
+    }
+
     /**
      * 组装job
      *
@@ -250,41 +257,4 @@ public class JobServiceImpl implements JobService {
             });
         }
     }
-
-    /**
-     * 创建线程池
-     *
-     * @return
-     */
-    protected ThreadPoolTaskExecutor createThreadPool() {
-        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
-        SysConfig sysConfigCustomThreadPoolCoreSize = commonCacheService.addSysConfigCache(SystemConstant.CUSTOM_THREAD_POOL_CORE_SIZE);
-        Optional.ofNullable(sysConfigCustomThreadPoolCoreSize).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("未配置是否自定义线程池大小"));
-        boolean customThreadPoolCoreSize = Boolean.valueOf(sysConfigCustomThreadPoolCoreSize.getConfigValue());
-
-        SysConfig sysConfigThreadPoolCoreSize = commonCacheService.addSysConfigCache(SystemConstant.THREAD_POOL_CORE_SIZE);
-        Optional.ofNullable(sysConfigThreadPoolCoreSize).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("未配置自定义线程池大小"));
-        Integer threadPoolCoreSize = Integer.valueOf(sysConfigThreadPoolCoreSize.getConfigValue());
-
-        final int cpuNum = Runtime.getRuntime().availableProcessors();
-        log.info("cpuNum:{}", cpuNum);
-        if (!customThreadPoolCoreSize && cpuNum > 0) {
-            threadPoolTaskExecutor.setCorePoolSize(Math.abs(cpuNum / 2));//核心线程数
-            threadPoolTaskExecutor.setMaxPoolSize(threadPoolTaskExecutor.getCorePoolSize() * 2);//最大线程数
-        } else {
-            threadPoolTaskExecutor.setCorePoolSize(threadPoolCoreSize);//核心线程数
-            threadPoolTaskExecutor.setMaxPoolSize(threadPoolCoreSize * 2);//最大线程数
-        }
-        threadPoolTaskExecutor.setKeepAliveSeconds(SystemConstant.THREAD_POOL_KEEP_ALIVE_SECONDS);//线程空闲时间
-        threadPoolTaskExecutor.setQueueCapacity(SystemConstant.THREAD_POOL_QUEUE_CAPACITY);//队列容量
-        threadPoolTaskExecutor.setThreadNamePrefix(SystemConstant.THREAD_POOL_NAME);
-        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);//设置是否允许核心线程超时。若允许,核心线程超时后,会被销毁。默认为不允许(fasle)
-        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);//设置shutdown时是否等到所有任务完成再真正关闭
-        threadPoolTaskExecutor.setAwaitTerminationSeconds(60 * 60 * 24);//当setWaitForTasksToCompleteOnShutdown(true)时,setAwaitTerminationSeconds 设置在 shutdown 之后最多等待多长时间后再真正关闭线程池
-        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
-        // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
-        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
-        threadPoolTaskExecutor.initialize();
-        return threadPoolTaskExecutor;
-    }
 }