public ThreadPoolExecutor( int corePoolSize, // 核心线程数 int maximumPoolSize, // 最大线程数 long keepAliveTime, // 非核心线程闲置回收时间 TimeUnit unit, // 时间单位 BlockingQueue<Runnable> workQueue, // 装载任务的阻塞队列 ThreadFactory threadFactory, // 线程创建工厂 RejectedExecutionHandler handler // 任务拒绝状态时处理策略 ) { // ...... }
状态变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0)); private static final int COUNT_BITS = Integer.SIZE - 3; private static final int CAPACITY = (1 << COUNT_BITS) - 1;
// runState is stored in the high-order bits private static final int RUNNING = -1 << COUNT_BITS; // 运行中 private static final int SHUTDOWN = 0 << COUNT_BITS; // 拒绝新任务 private static final int STOP = 1 << COUNT_BITS; // 拒绝新任务且不处理剩余任务 private static final int TIDYING = 2 << COUNT_BITS; // 所有线程停止,准备执行终止方法 private static final int TERMINATED = 3 << COUNT_BITS; // 已执行终止方法
// 线程状态 ctl值取低29位 private static int runStateOf(int c) { return c & ~CAPACITY; } // 线程状态 ctl值取高3位 private static int workerCountOf(int c) { return c & CAPACITY; } private static int ctlOf(int rs, int wc) { return rs | wc; }
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
newSingleThreadExecutor
单线程化的线程池:
有且仅有一个工作线程执行任务 所有任务按照指定顺序执行,即遵循队列的入队出队规则
1 2 3 4 5 6
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
newScheduledThreadPool
支持定时以指定周期循环执行任务:
1 2 3
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }