• Concurrent


    原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11426981.html

    ThreadPoolExecutor底层方法参数:

    @param corePoolSize: the number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is set

    @param maximumPoolSize: the maximum number of threads to allow in the pool

    @param 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.

    @param unit: the time unit for the {@code keepAliveTime} argument

    @param workQueue: the queue to use for holding tasks before they are executed.  This queue will hold only the {@code Runnable} tasks submitted by the {@code execute} method.

    @param threadFactory: the factory to use when the executor creates a new thread

    @param handler: the handler to use when execution is blocked because the thread bounds and queue capacities are reached 

    Reject策略预定义有四种: 

    (1)ThreadPoolExecutor.AbortPolicy策略,是默认的策略,处理程序遭到拒绝将抛出运行时 RejectedExecutionException。 

    (2)ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃. 

    (3)ThreadPoolExecutor.DiscardPolicy策略,不能执行的任务将被丢弃. 

    (4)ThreadPoolExecutor.DiscardOldestPolicy策略,如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程)

    ThreadPoolExecutor执行器的处理流程: 

    (1)当线程池大小小于corePoolSize就新建线程,并处理请求. 

    (2)当线程池大小等于corePoolSize,把请求放入workQueue中,池子里的空闲线程就去从workQueue中取任务并处理. 

    (3)当workQueue放不下新入的任务时,新建线程加入线程池,并处理请求,如果池子大小撑到了maximumPoolSize就用RejectedExecutionHandler来做拒绝处理. 

    (4)另外,当线程池的线程数大于corePoolSize的时候,多余的线程会等待keepAliveTime长的时间,如果无请求可处理就自行销毁.

     1 package org.fool.test.thread;  
     2   
     3 import java.util.concurrent.LinkedBlockingQueue;  
     4 import java.util.concurrent.ThreadFactory;  
     5 import java.util.concurrent.ThreadPoolExecutor;  
     6 import java.util.concurrent.TimeUnit;  
     7 import java.util.concurrent.atomic.AtomicInteger;  
     8   
     9 public class ThreadPoolExecutorTest {  
    10     public static void main(String[] args) {  
    11         ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 3, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(5), new ThreadFactory() {  
    12             private final AtomicInteger threadNum = new AtomicInteger(0);  
    13   
    14             @Override  
    15             public Thread newThread(Runnable r) {  
    16                 return new Thread(r, "thread-" + threadNum.getAndIncrement());  
    17             }  
    18         });  
    19   
    20         for (int i = 0; i < 8; i++) {  
    21             int index = i;  
    22   
    23             executor.execute(() -> {  
    24                 try {  
    25                     Thread.sleep(3000);  
    26                 } catch (InterruptedException e) {  
    27                     e.printStackTrace();  
    28                 }  
    29                 System.out.println(Thread.currentThread().getName() + " invoked task:" + index);  
    30             });  
    31         }  
    32     }  
    33 }   

    例子中 corePoolSize:1, maximumPoolSize: 3, 有界队列容量是5

    查看结果输出,可以看到总共执行8个任务0到7,超过了有界队列的容量5,线程1和线程2就优先处理超过有界队列容量的任务6和任务7,就好比银行柜台3个窗口,先开1个窗口处理业务,5个人在排队,有第6个,第7个人来办理的业务的时候,就开第2个,第3个窗口来处理业务。

    如何合理的配置Java线程池?如CPU密集型的任务,基本线程池应该配置多大?IO密集型的任务,基本线程池应该配置多大?用有界队列好还是无界队列好?任务非常多的时候,使用什么阻塞队列能获取最好的吞吐量?

    要想合理的配置线程池,就必须首先分析任务特性,可以从以下几个角度来进行分析:

    任务的性质:CPU密集型任务,IO密集型任务和混合型任务。

    任务的优先级:高,中和低。

    任务的执行时间:长,中和短。

    任务的依赖性:是否依赖其他系统资源,如数据库连接。

    任务性质不同的任务可以用不同规模的线程池分开处理。

    • CPU密集型任务配置尽可能少的线程数量,如配置Ncpu+1个线程的线程池。
    • IO密集型任务则由于需要等待IO操作,线程并不是一直在执行任务,则配置尽可能多的线程,如2*Ncpu。
    • 混合型的任务,如果可以拆分,则将其拆分成一个CPU密集型任务和一个IO密集型任务,只要这两个任务执行的时间相差不是太大,那么分解后执行的吞吐率要高于串行执行的吞吐率,如果这两个任务执行时间相差太大,则没必要进行分解。我们可以通过Runtime.getRuntime().availableProcessors()方法获得当前设备的CPU个数。

    优先级不同的任务可以使用优先级队列PriorityBlockingQueue来处理。它可以让优先级高的任务先得到执行,需要注意的是如果一直有优先级高的任务提交到队列里,那么优先级低的任务可能永远不能执行。

    执行时间不同的任务可以交给不同规模的线程池来处理,或者也可以使用优先级队列,让执行时间短的任务先执行。

    依赖数据库连接池的任务,因为线程提交SQL后需要等待数据库返回结果,如果等待的时间越长CPU空闲时间就越长,那么线程数应该设置越大,这样才能更好的利用CPU。

    建议使用有界队列,有界队列能增加系统的稳定性和预警能力,可以根据需要设大一点,比如几千。有一次我们组使用的后台任务线程池的队列和线程池全满了,不断的抛出抛弃任务的异常,通过排查发现是数据库出现了问题,导致执行SQL变得非常缓慢,因为后台任务线程池里的任务全是需要向数据库查询和插入数据的,所以导致线程池里的工作线程全部阻塞住,任务积压在线程池里。如果当时我们设置成无界队列,线程池的队列就会越来越多,有可能会撑满内存,导致整个系统不可用,而不只是后台任务出现问题。当然我们的系统所有的任务是用的单独的服务器部署的,而我们使用不同规模的线程池跑不同类型的任务,但是出现这样问题时也会影响到其他任务。

    Reference

    http://ifeve.com/thread-pools/

    http://ifeve.com/java-threadpool/

  • 相关阅读:
    Gevent高并发网络库精解
    python多线程参考文章
    python多线程
    进程与线程
    golang 微服务以及相关web框架
    微服务实战:从架构到发布
    python 常用库收集
    总结数据科学家常用的Python库
    20个最有用的Python数据科学库
    自然语言处理的发展历程
  • 原文地址:https://www.cnblogs.com/agilestyle/p/11426981.html
Copyright © 2020-2023  润新知