1.Thread pool创建
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
参数解释:
corePoolSize 核心线程池大小
When a new task is submitted in method [execute(Runnable)], and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle
maximumPoolSize 线程池最大容量大小
If there are more than corePoolSize but less than maximumPoolSize threads running, a new thread will be created only if the queue is full
BlockingQueue 阻塞队列
Any [BlockingQueue]may be used to transfer and hold submitted tasks
If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing.
If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.
If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected.
三个一般的策略
- 直接交接
default 实现 -- SynchronousQueue
特点:不会持有任何task,直接抛给Thread来执行,如果当前没有可用线程,且不可申请新线程,任务会被拒绝、通常为了避免任务拒绝,会指定maximumPoolSize为最大值,避免任务被拒绝。
2.无限队列
default 实现 -- LinkedBlockingQueue
特点:如果所有的corePoolSize都在busy的状态,将会把task入队列,不会创建新的线程,直到有线程空闲
3.有限队列
default 实现 -- ArrayBlockingQueue
特点:队列大小有限,当队列已满,将去创建新的线程,如果已经达到maximumPoolSize,任务会被拒绝
3.类型判断
CPU密集
所谓CPU密集型就是指系统大部分时间是在做程序正常的计算任务,例如数字运算、赋值、分配内存、内存拷贝、循环、查找、排序等,这些处理都需要CPU来完成。
IO密集
IO密集型的话,是指系统大部分时间在跟I/O交互,而这个时间线程不会占用CPU来处理,即在这个时间范围内,可以由其他线程来使用CPU,因而可以多配置一些线程。
混合型
混合型的话,是指两者都占有一定的时间。