ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
corePoolSize 核心线程数 当线程数<corePoolSize时,新建线程。java
maxinumPoolSize 最大线程数线程
keepAliveTime 存活时间 当线程数>corePoolSize时,空闲线程存活的最长时间code
timeUnit 单位时间继承
workQueue 保存任务的阻塞队列队列
threadFactory 线程建立工厂get
handler 拒绝策略it
拒绝策略默认有4种 1.抛出异常 2.直接丢弃 3.丢弃队列中最老的 4.直接调用run方法,阻塞执行。 固然也能够继承RejectedExecutionHandler实现本身的拒绝策略io
由于参数比较多,java中的Exectors提供了简便的线程池建立方式。thread
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
能够看到用的workQueue是LinkedBlockingQueue,说明队列无限长,线程池最大值就是入参nThreads。线程池
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
SynchronousQueue是容量为1的阻塞队列,因此新增任务的时候会新起线程,线程数最大值为Integer.MAX_VALUE
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
不用说了,线程数最大为1。
继承于Future,可以实现带返回值的线程执行结果。 几个特殊方法, isDone() get(),get(Long timeOut,TimeUtil) cancel(),isCancel()