自定义线程池

package com.sunwayland.mes.report.util;

import com.sunwayland.mes.report.config.CustomThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

/**
*
* 线程池工具,用来创建线程池,并提供将任务添加到线程池的方法<br>
*
* 固定线程数为50,超过时放入无界队列中等待.<br>
*
* 使用方法: 假如要把<br>
* registService.saveRegist(prpLregist); <br>
* 放到单独线程执行,则:
*
* <pre>
* ThreadPoolUtils.exec(new Runnable() {
* public void run() {
* registService.saveRegist(prpLregist);
* }
* });
* </pre>
*
* 线程并行提交并最后要获取线程的执行结果,使用方法:
* <pre>
* Future future = ThreadPoolUtils.exec(new TaskTest());
*
* public class TaskTest implements Callable<String> {
* public String call() {
* return "Hello World!";
* }
* }
* future.get()获取线程执行返回的结果
* </pre>
*
* 注意:新线程与启动线程相互独立,hibernate session不共享、事务不传递,所以不支持传入可能懒加载的对象。
*/
public class ThreadPoolUtils {
private final static Logger logger = LoggerFactory.getLogger(ThreadPoolUtils.class);
/**
* 核心线程池大小
*/
public static final int CORE_POOL_SIZE = 100;
/**
* 最大线程池大小
*/
public static final int MAX_POOL_SIZE = 200;
/**
* 阻塞任务队列大小
*/
public static final int QUEUE_CAPACITY = 2048;
/**
* 空闲线程存活时间
*/
public static final Long KEEP_ALIVE_TIME = 30L;

private static final ThreadPoolExecutor exec = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(QUEUE_CAPACITY),
new CustomThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());

/**
* 禁止实例化
*/
private ThreadPoolUtils() {

}

/**
* 提交任务
*/
public static void exec(Runnable task) {
ThreadPoolUtils.catThreadPoolInfo();
exec.submit(task);
}

/**
* 并行提交任务并获取线程执行后返回的结果
* @param: task
* @return:
*/
public static Future<?> execCallable(Callable<?> task) {
ThreadPoolUtils.catThreadPoolInfo();
return exec.submit(task);
}
/**
* 并行提交任务并获取线程执行后返回的结果
* @param: task
* @return:
*/
public static void catThreadPoolInfo() {
logger.info("当前排队线程数:{}",exec.getQueue().size());
logger.info("当前活动线程数:{}",exec.getActiveCount());
logger.info("执行完成线程数:{}",exec.getCompletedTaskCount());
logger.info("总线程数:{}",exec.getTaskCount());
}
}
posted @ 2022-05-31 09:07  陈秋白  阅读(430)  评论(0编辑  收藏  举报