wg-basic/basic-util/src/main/java/ink/wgink/util/thread/CachedThreadPoolUtil.java
2022-06-04 11:35:24 +08:00

84 lines
2.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package ink.wgink.util.thread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @ClassName: CachedThreadPoolUtil
* @Description: 缓存线程池
* @Author: wanggeng
* @Date: 2022/5/20 00:27
* @Version: 1.0
*/
public class CachedThreadPoolUtil {
private static final Logger LOG = LoggerFactory.getLogger(CachedThreadPoolUtil.class);
/**
* 最多66个线程保持60s
*/
private static ExecutorService executorService = new ThreadPoolExecutor(0, 66,
60L, TimeUnit.SECONDS,
new SynchronousQueue<>());
/**
* 执行线程
*
* @param runnable
*/
public static void execute(Runnable runnable) {
LOG.debug("****************** execute");
executorService.execute(runnable);
}
/**
* 状态
*
* @return
*/
public static Status getStatus() {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executorService;
return new Status(threadPoolExecutor.getQueue().size(),
threadPoolExecutor.getActiveCount(),
threadPoolExecutor.getCompletedTaskCount(),
threadPoolExecutor.getTaskCount());
}
public static class Status {
private Integer queueSize;
private Integer activeCount;
private Long completedTaskCount;
private Long totalTaskCount;
public Status(Integer queueSize, Integer activeCount, Long completedTaskCount, Long totalTaskCount) {
this.queueSize = queueSize;
this.activeCount = activeCount;
this.completedTaskCount = completedTaskCount;
this.totalTaskCount = totalTaskCount;
}
public Integer getQueueSize() {
return queueSize == null ? 0 : queueSize;
}
public Integer getActiveCount() {
return activeCount == null ? 0 : activeCount;
}
public Long getCompletedTaskCount() {
return completedTaskCount == null ? 0 : completedTaskCount;
}
public Long getTotalTaskCount() {
return totalTaskCount == null ? 0 : totalTaskCount;
}
}
}