笔记 线程池ThreadPoolExecutor

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);
使用了延时队列,用来实现定时任务。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值