Executor接口
E
Executor接口提供了执行方法,在Executor实例中传入任务实例(Runnable函数式接口中只有一个run方法表示要执行的事),就会新建线程执行任务,或是加入等待队列,或者拒绝执行抛出RejectedExecutionException。
ThreadPoolExecutor实现类
ThreadPoolExecutor类是Java中线程池Executor的具体实现类,它的构造函数最多有七个参数,先解析一下:
int corePoolSiz 线程池核心线程数量
int maximumPoolSize 线程池最大线程数量
long keepAliveTime 临时线程最大闲置时间
TimeUnit unit keepAliveTime时间单位
BlockingQueue<Runnable> workQueue 任务队列
ThreadFactory threadFactory 见名知意,线程工厂
RejectedExecutionHandler handler 拒绝服务处理方法
前五个是必须有的,后面俩根据自己需要添加。
贴execute源码:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
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);
}
执行策略如下:
1.线程池中创建的线程小于核心线程数量,则创建一个新线程
2.将任务移入等待队列
3.创建新的临时线程执行任务
4.核心线程和临时线程达到最大值,任务队列也满,抛出RejectExecutionExeception
ExecutorService接口
这个接口是线程管理接口,用于销毁线程池,返回任务列表等
关闭线程池方法
shutdown
线程池不再接受新的任务,但也不会终止正在执行的任务
void shutdown();
shutdownNow()
立刻关闭线程池,终止正在执行的任务,返回尚未开始的任务。
List<Runnable> shutdownNow();
Executors类
用来创建特定的线程池常用四种介绍:
1.单线程线程池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
2.定长线程池
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
3.缓存线程池
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
4.ScheduledThreadPoolExecutor
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
ScheduledThreadPoolExecutor
拒绝服务策略
1.AbortPolicy-中止策略
这是默认的拒绝服务策略,放弃执行该任务,然后抛出RejectedExecutionException错误
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
2.DiscardPolicy-丢弃策略
放弃执行该任务,并且不会抛出异常
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {}
3.DiscardOldestPolicy-丢弃旧任务策略
放弃待执行队列中的第一个任务,随后重新执行该任务
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
4.CallerRunsPolicy-交给调用者
run()方法的妙用
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}