Implementing thread pool calls

[Foreword]
In actual work, new Thread is rarely executed for multi-threading, but a thread pool is created, and then the thread pool resources are called.
Just like connecting to a database, I never say that JDBC is used to establish a connection, but a database connection pool. Netty communication also builds a Channel channel pool.
To build a JDBC separately, you need to load the driver, write the URL database configuration information, and close the connection. It is very troublesome to have to do it every time. The same is true for new Thread. Every new Thread needs to create a new object, and the thread also lacks unified management. It is impossible to name the thread every time. If you accidentally create a new thread in the loop, it may appear, and new threads will be created continuously Until it crashes, some advanced functions, more execution, regular execution, and thread interruption are not available.
The thread pool is different. The premise is that threads can be built and reused. The maximum number of concurrent threads is set, and there will be no unlimited new threads. Advanced functions such as regular execution, regular execution, and concurrency control are also available.
[Text]
Thread pool -- ThreadPoolExecutor

    public void ThreadPoolExecutor(int corePoolSize, 
               int maximumPoolSize, 
               long keepAliveTime,
               TimeUnit unit, 
               BlockingQueue workQueue,
               ThreadFactory threadFactory, 
               RejectedExecutionHandler handler) {
    }
    corePoolSize    核心线程数量
    maximumPoolSize    最大线程数量    
    keepAliveTime      空闲线程存活时间
    unit    存活时间的单位
    workQueue    阻塞队列,存储等待执行的任务,很重要,对线程池运行影响很大
    threadFactory    线程工厂,创建管理线程
    handler    拒绝处理任务时的策略

    如果存活线程数<核心线程数,直接创建新线程,一般发生在线程池初始化时(维持一定数量备调用);
    如果存活线程数,处于核心和最大之间,阻塞队列没满,先放队列里,只有阻塞队列满,才创建新线程;
    如果存活线程数,超过最大线程数,且阻塞队列满,执行拒绝策略
    好理解的:南京市民大厅,至少开5个窗口(核心线程),市民(任务)超过5个,大厅长椅(阻塞队列)坐得下,就不开新窗口(线程),大厅里坐不下,还有空余窗口(最大线程),就多开窗口,要是窗口全开了,大厅还坐不下,就通知暂停发号(拒绝策略)。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325126068&siteId=291194637