Java教程:线程池工具类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 线程池工具类
*
* @author wfeil211@foxmail.com
* @version 2021-7-14 16:24:45
*/
public class ThreadPoolManager {
private static String threadPoolName;
/**
* 最大线程池大小
*/
private int maxThread = 0;
private ThreadPoolExecutor executor = null;
private static final Logger logger = LoggerFactory.getLogger(ThreadPoolManager.class);
/**
* 测试A的线程池
*/
private static ThreadPoolManager poolA;
public ThreadPoolManager(int maxThread, int maxQueue, String threadPoolName) {
ThreadPoolManager.threadPoolName = threadPoolName;
this.maxThread = maxThread;
/** 队列未来的大小已知時使用 */
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(maxQueue);
this.executor = new ThreadPoolExecutor(maxThread, maxThread, 60L, TimeUnit.SECONDS, workQueue);
logger.info("线程池初始化,线程池大小:" + maxThread + " 队列大小:" + maxQueue);
}
public static synchronized ThreadPoolManager getPoolA() {
if (poolA != null) {
return poolA;
}
/** 最大线程池大小 和最大队列大小 */
poolA = new ThreadPoolManager(8, 10, "线程池");
return poolA;
}
/**
* 线程执行
*
* @param runnable 任务
* @return -1 队列已满 0 立即执行 >0排队中
*/
public void exec(Runnable runnable) {
try {
/** 加入线程池并执行 */
executor.execute(runnable);
int count = executor.getActiveCount();
if (count >= maxThread) {
count = executor.getQueue().size();
logger.info("任务[" + runnable.toString() + "]加入排队中:" + count);
} else {
logger.info("任务[" + runnable.toString() + "]开始执行");
}
} catch (Exception e) {
logger.info(threadPoolName + "线程忙,稍等10ms");
try {
Thread.sleep(10);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
/** 迭代调用 */
exec(runnable);
}
}
/**
* 线程执行
*
* @param runnable 任务
* @return -1 队列已满 0 立即执行 >0排队中
*/
public int execute(Runnable runnable) {
try {
/** 加入线程池并执行 */
executor.execute(runnable);
int count = executor.getActiveCount();
if (count >= maxThread) {
count = executor.getQueue().size();
} else {
count = 0;
}
return count;
} catch (Exception e) {
return -1;
}
}
public boolean isRunning() {
int count = executor.getActiveCount();
return count >= 1;
}
public void shutdown() {
if (executor != null && !executor.isShutdown()) {
executor.shutdown();
logger.info("线程池关闭");
}
}
}