ThreadPoolExecutor
ThreadPoolExecutor extends AbstractExecutorService
An {@link ExecutorService} that executes each submitted task using one of possibly several pooled threads, normally configured using {@link Executors} factory methods
public abstract class AbstractExecutorService implements ExecutorService
Provides default implementations of {@link ExecutorService} execution methods.
public interface ExecutorService extends Executor
An {@link Executor} that provides methods to manage termination and methods that can produce a {@link Future} for tracking progress of one or more asynchronous tasks。
public interface Executor
An object that executes submitted {@link Runnable} tasks
执行器接口,将任务的提交和执行分开,增加了程序设计灵活性。
核心方法:
1.构造方法:构造相关线程池
public ThreadPoolExecutor(int corePoolSize, //核心线程数
int maximumPoolSize, //最大线程数
long keepAliveTime, //空闲时间 非核心线程空闲时间超过这个值会被回收
TimeUnit unit, //空闲时间单位
BlockingQueue<Runnable> workQueue,//阻塞队列
ThreadFactory threadFactory, //线程工厂 线程池通过线程工程获取线程
RejectedExecutionHandler handler) //拒绝策略
2.提交执行任务的方法
public void execute(Runnable command)
如果当前线程数小于核心数,直接新建一个核心线程执行任务
如果核心线程已满,任务加入阻塞队列
如果阻塞队列也满了,但当前线程数小于线程数允许的最大值,就新建一个非核心线程执行任务
如果阻塞队列满了,线程数也到了最大值,就执行拒绝策略。
3.尝试新建线程任务
private boolean addWorker(Runnable firstTask, boolean core)
4.执行逻辑
final void runWorker(Worker w)
常用线程池
ExecutorService cachedPool = Executors.newCachedThreadPool();
核心线程数为0,最大线程数是Integer.MAX_VALUE, 队列无法加入任务,来了任务就创建非核心线程去执行。
ExecutorService fixedPool = Executors.newFixedThreadPool(5);
核心线程数等于最大线程数,队列的长度Integer.MAX_VALUE。
ExecutorService single = Executors.newSingleThreadExecutor();
核心线程数等于最大线程数等于1。
ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(5);
使用了延时队列,用来实现定时任务。