使用线程池的好处:
- 重用线程,线程的创建和销毁是很耗时的。
- 控制线程的数量。
线程池工具类:
ThreadPool.java
package com.zws.thread.pool; import java.util.concurrent.Callable; import java.util.concurrent.Future; /** * * @author wensh.zhu * */ public interface ThreadPool { void execute(Runnable task); <T> Future<T> submit(Callable<T> task); /** * 线程池是否繁忙 * @return */ boolean isBusy(); }
SimpleThreadPool.java
package com.zws.thread.pool; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * * @author wensh.zhu * */ public class SimpleThreadPool implements ThreadPool{ private static int corePoolSize = 30, maximumPoolSize = 50, capacity = 50000; private static long keepAliveTime = 30 * 1000l; private static LinkedBlockingQueue<Runnable> workQueue; private static ThreadPoolExecutor executor; private static SimpleThreadPool pool = new SimpleThreadPool(); private SimpleThreadPool() { workQueue = new LinkedBlockingQueue<Runnable>(capacity); executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, workQueue, new RejectionHandler()); } public static SimpleThreadPool newInstance() { return pool; } public void execute(Runnable task) { executor.execute(task); } public <T> Future<T> submit(Callable<T> task) { return executor.submit(task); } public boolean isQueueFull() { return workQueue.size() == capacity; } public int queueSize() { return workQueue.size(); } public boolean isBusy() { return executor.getPoolSize() == maximumPoolSize && isQueueFull(); } public int poolSize() { return executor.getPoolSize(); } }
RejectionHandler.java
package com.zws.thread.pool; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; /** * * @author wensh.zhu * */ public class RejectionHandler implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { System.out.println("task " + r + " execute fail"); } }
解释ThreadPoolExecutor类构造函数的参数:
corePoolSize:核心线程数,线程池保有的线程的数量,如果allowCoreThreadTimeOut
参数不设置,即使这些线程空闲也不会被回收。也就是说如果allowCoreThreadTimeOut
参数不设置那么当线程池内的线程的数量升至大于等于corePoolSize后,线程池至少会保有corePoolSize数量的线程。
workQueue:线程池工作队列,当线程池内线程的数量达到corePoolSize并且这些线程都处于忙碌状态时,那么后续提交至线程池的任务会被缓存至工作队列中,当线程池内有空闲线程时就会从此工作队列中取任务并执行。
maximumPoolSize:线程池所允许的最大线程的数量,当工作队列满时,线程池会继续创建新的线程,但是线程池内总线程数量不会超过maximumPoolSize。
keepAliveTime:当线程池内线程的数量超过corePoolSize时,超出部分线程的空闲等待时间,当空闲时间超过此值则超出部分线程就会被回收。
unit:keepAliveTime的单位。
handler:线程池任务拒绝策略接口,当工作队列满并且线程池忙碌线程数量达到maximumPoolSize后,后续提交至线程池的任务会被拒绝,此时回调此接口,自己实现具体的拒绝策略。如果此接口没有指定则报java.util.concurrent.RejectedExecutionException异常。
时间: 2024-10-28 13:23:29