线程池:
提示:线程池相关必备内容
两种创建方式:
- Executors(项目中不推荐使用)
- ThreadPoolExecutor
ThreadPoolTaskExecutor是 Spring 的线程池技术,在spring core包中,ThreadPoolTaskExecutor是对ThreadPoolExecutor进行了封装处理。
七个核心参数:
- corePoolSize
- maximumPoolSize
- keepAliveTime
- timeUnit
- blockingQueue
- threadFactory
- rejectedExecutionHandler
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler){
...
}
决绝策略:
- AbortPolicy (默认的策略)
- CallerRunsPolicy
- DiscardPolicy
- DiscardOldestPolicy
(1)ThreadPoolExecutor.AbortPolicy —— 默认的策略,它会抛出“拒绝执行”异常。
(2)ThreadPoolExecutor.CallerRunsPolicy —— 它在执行方法的调用线程中直接运行被拒绝的任务,除非已关闭执行器,在这种情况下,该任务将被丢弃。
(3)ThreadPoolExecutor.DiscardPolicy —— 它会默默地丢弃被拒绝的任务。
(4)ThreadPoolExecutor.DiscardOldestPolicy —— 它会丢弃最旧的未处理请求,然后重试执行,除非执行器已关闭,在这种情况下,任务将被丢弃。
线程池状态:
- RUNNING
- SHUTDOWN
- STOP
- TIDYING
- TERMINATED
execute()和submit()
execute方法
Executor接口中
public interface Executor {
void execute(Runnable command);
}
submit方法
ExecutorService接口中
public interface ExecutorService extends Executor {
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
}
执行任务流程
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* 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);
}
1821

被折叠的 条评论
为什么被折叠?



