先贴出一个创建线程池的实例:
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolDemo { private ThreadPoolExecutor threadPool = null ; public ThreadPoolDemo(){ threadPool = new ThreadPoolExecutor(5, 10, 30, TimeUnit.SECONDS, new LinkedBlockingQueue() , new ThreadNameFactory("myThread", false) , new MyAbortPolicy("ThreadName")) ; } }
import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; public class ThreadNameFactory implements ThreadFactory{ private static AtomicInteger curThre = new AtomicInteger(1) ; private AtomicInteger threadNum = new AtomicInteger(1); private String namePre ; private boolean isW ; private final ThreadGroup mGroup; public ThreadNameFactory(String namePre , boolean isW){ this.namePre = namePre +"-"+curThre.getAndIncrement() ; this.isW = isW ; SecurityManager sys = System.getSecurityManager() ; mGroup = ( sys == null ) ? Thread.currentThread().getThreadGroup() : sys.getThreadGroup(); } @Override public Thread newThread(Runnable arg0) { Thread thread = new Thread(mGroup , this.namePre+"-"+threadNum.getAndIncrement() ); thread.setDaemon(isW); return thread; } }
import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; public class MyAbortPolicy extends AbortPolicy{ private String runName ; public MyAbortPolicy(String runName){ this.runName = runName ; } @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { String msg = String.format("Thread pool is EXHAUSTED!" + " Thread Name: %s, Pool Size: %d (active: %d, core: %d, max: %d, largest: %d), Task: %d (completed: %d)," + " Executor status:(isShutdown:%s, isTerminated:%s, isTerminating:%s)" , runName, e.getPoolSize(), e.getActiveCount(), e.getCorePoolSize(), e.getMaximumPoolSize(), e.getLargestPoolSize(), e.getTaskCount(), e.getCompletedTaskCount(), e.isShutdown(), e.isTerminated(), e.isTerminating()); throw new RejectedExecutionException(msg); } }
构造方法:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueueworkQueue, ThreadFactory threadFactory , RejectedExecutionHandler handler) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler); }
参数解释:
corePoolSize: 核心线程数,会一直存活,即使没有任务,线程池也会维护线程的最少数量
maximumPoolSize: 线程池维护线程的最大数量
keepAliveTime: 线程池维护线程所允许的空闲时间,当线程空闲时间达到keepAliveTime,该线程会退出,直到线程数量等于corePoolSize。如果allowCoreThreadTimeout设置为true,则所有线程均会退出直到线程数量为0。
unit:线程池维护线程所允许的空闲时间的单位、可选参数值为:TimeUnit中的几个静态属性:NANOSECONDS、MICROSECONDS、MILLISECONDS、SECONDS。
workQueue:线程池所使用的缓冲队列,常用的是:java.util.concurrent.ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue
handler:线程池中的数量大于maximumPoolSize,对拒绝任务的处理策略,默认值ThreadPoolExecutor.AbortPolicy()。
threadFactory :线程生成工厂