用java生成线程池工具类
时间: 2023-11-28 22:42:15 浏览: 89
Java提供了Executor框架来创建和管理线程池。线程池可以提高程序的性能和可扩展性,避免了线程的频繁创建和销毁,同时也可以控制线程的数量和执行顺序。下面是一个简单的Java线程池工具类的实现:
```
public class ThreadPoolUtil {
private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();
private static final int MAX_POOL_SIZE = 2 * CORE_POOL_SIZE;
private static final int KEEP_ALIVE_TIME = 0;
private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>();
private static final ThreadFactory THREAD_FACTORY = Executors.defaultThreadFactory();
private static final RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.AbortPolicy();
private static ThreadPoolExecutor threadPoolExecutor;
private ThreadPoolUtil() {
}
public static synchronized ThreadPoolExecutor getThreadPoolExecutor() {
if (threadPoolExecutor == null) {
threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TIME_UNIT, WORK_QUEUE, THREAD_FACTORY, HANDLER);
}
return threadPoolExecutor;
}
}
```
这个工具类使用了单例模式来保证线程池对象的唯一性。其中,核心线程数和最大线程数都是根据CPU核心数来计算的,拒绝策略使用了默认的AbortPolicy。你可以根据自己的需求来调整这些参数。
阅读全文