1. 线程生命周期
2.submit、executor区别
- submit是有返回值 executor无返回值
Java线程池类关系
1.java.util.concurrent.Executor 执行接口 execute 第一层
2.java.util.concurrent.ExecutorService 提交接口 submit 第二层
3.java.util.concurrent.ThreadPoolExecutor把执行接口和提交接口
整合合并 第三层
4.java.util.concurrent.ThreadPoolExecutor Java普通线程池 第四层
public ThreadPoolExecutor(int corePoolSize,核心线程数
int maximumPoolSize,最大线程数
long keepAliveTime,保持时间
TimeUnit unit,时间单位
BlockingQueue<Runnable> workQueue,阻塞队列
ThreadFactory threadFactory,线程工厂
RejectedExecutionHandler handler 拒绝策略)
2.ThreadPool
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
3. 拒绝策略默认使用AbortPolicy
/**
* The default rejected execution handler
*/
private static final RejectedExecutionHandler defaultHandler =
new AbortPolicy();