线程

Day30.线程

ThreadPoolExecutor源码分析

一、Java构建线程方式

  1. 继承thread类

    public class TestThread extends Thread {}
    
  2. 实现Runnable

  3. 实现Callable,可以返回值

  4. 线程池方式(java 提供了构建线程池的方式)

    Executors
    

    规范中不允许使用下面的方式创建线程池,这种方式对线程控制力度比较低,推荐手动创建线程池.

    ExecutorService executorService = Executors.newFixedThreadPool(1);
    

二、线程池7个参数

  • corePoolSize:线程数

  • maximumPoolSize:最大线程数

  • keepAliveTime:空闲时间

  • unit:keepAliveTime参数的时间单位

  • workQueue:阻塞队列

  • threadFactory:线程工厂.可以给线程指定一个名称

  • handler:拒绝策略

    Creates a new ThreadPoolExecutor with the given initial parameters.
    形参:
    corePoolSize – the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
    maximumPoolSize – the maximum number of threads to allow in the pool
    keepAliveTime – when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
    unit – the time unit for the keepAliveTime argument
    workQueue – the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
    threadFactory – the factory to use when the executor creates a new thread
    handler – the handler to use when execution is blocked because the thread bounds and queue capacities are reached
    抛出:
    IllegalArgumentException – if one of the following holds: corePoolSize < 0 keepAliveTime < 0 maximumPoolSize <= 0 maximumPoolSize < corePoolSize
    NullPointerException – if workQueue or threadFactory or handler is null
    
    public ThreadPoolExecutor(int corePoolSize,
                                  int maximumPoolSize,
                                  long keepAliveTime,
                                  TimeUnit unit,
                                  BlockingQueue<Runnable> workQueue,
                                  ThreadFactory threadFactory,
                                  RejectedExecutionHandler handler) {...}
    

三、线程池的执行流程

  • 线程池执行流程

    image-20220518154336976

posted @ 2022-05-18 15:48  雨溟  阅读(26)  评论(0)    收藏  举报