线程池问题1 、2 、3

1.Thread pool创建

ThreadPoolExecutor

  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.

三个一般的策略

  1. 直接交接
    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,因而可以多配置一些线程。

混合型
混合型的话,是指两者都占有一定的时间。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 起风了 抚摸我,引诱我 我从未抵抗过,甚至 我试着用尽力气去热吻风 我知道的 那阵风迟早会爱抚过你的脸庞
    我是赵眠阅读 1,292评论 0 0
  • 欢迎来到博星教育108将讲师朱老师课堂,这里是朱老师第243条早安问候。 没有奋斗,就没有力量(Where t...
    高飞1阅读 1,346评论 0 0
  • 开车去接儿子,我俩有一搭没一搭地聊着。我给他带了点水果一一桃子。他边吃边和我聊,突然,儿子像发现新大陆似地告诉我,...
    陈宁儿童与家庭教育研究院阅读 2,629评论 2 4

友情链接更多精彩内容