2

android线程学习—线程池2

 3 years ago
source link: http://www.demanmath.com/index.php/2021/01/18/androidxianchengxuexi-xianchengchi2/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

线程池的创建

ThreadPoolExecutor详解:
构造函数的参数含义如下:

  • corePoolSize:指定了线程池中的线程数量,它的数量决定了添加的任务是开辟新的线程去执行,还是放到workQueue任务队列中去;

  • maximumPoolSize:指定了线程池中的最大线程数量,这个参数会根据你使用的workQueue任务队列的类型,决定线程池会开辟的最大线程数量;

  • keepAliveTime:当线程池中空闲线程数量超过corePoolSize时,多余的线程会在多长时间内被销毁;

  • unit:keepAliveTime的单位

  • workQueue:任务队列,被添加到线程池中,但尚未被执行的任务;它一般分为直接提交队列、有界任务队列、无界任务队列、优先任务队列几种;

  • threadFactory:线程工厂,用于创建线程,一般用默认即可;

  • handler:拒绝策略;当任务太多来不及处理时,如何拒绝任务;

线程逻辑如下:

线程池和队列

linkedBlockQueue,ArrayBlockQueue,DelayQueue,SynchronizedQueue

SynchronizedQueue

参考https://www.cnblogs.com/hongdada/p/6147834.html
它是一个很特殊的queue,每次只能有一个对象在queue里面。queue的方法都是特殊的。
它的作用:要理解它的作用,首先的理解它是一个阻塞的队列。队列的容量是无接的,但是它只要有1个元素,就会阻塞,随意队列长度是0.
用它的原因就是阻塞,线程调度。

LinkedBlockingQueue

LinkedBlockingQueue是一个无界缓存等待队列,所以对于的runnable都在队列里面。

ArrayBlockingQueue

这是一个有界的队列,当线程数到了core 线程数以后,新的runnable放入队列里面。继续增加的时候,新建线程。当这些新建的线程到达max以后,就会抛出异常。

DelayQueue


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK