【高并发】从源码角度分析创建线程池究竟有哪些方式

{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"大家好,我是冰河~~","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在Java的高并发领域,线程池一直是一个绕不开的话题。有些童鞋一直在使用线程池,但是,对于如何创建线程池仅仅停留在使用Executors工具类的方式,那么,创建线程池究竟存在哪几种方式呢?就让我们一起从创建线程池的源码来深入分析究竟有哪些方式可以创建线程池。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"使用Executors工具类创建线程池","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在创建线程池时,初学者用的最多的就是Executors 这个工具类,而使用这个工具类创建线程池时非常简单的,不需要关注太多的线程池细节,只需要传入必要的参数即可。Executors 工具类提供了几种创建线程池的方法,如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Executors.newCachedThreadPool:创建一个可缓存的线程池,如果线程池的大小超过了需要,可以灵活回收空闲线程,如果没有可回收线程,则新建线程","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Executors.newFixedThreadPool:创建一个定长的线程池,可以控制线程的最大并发数,超出的线程会在队列中等待","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Executors.newScheduledThreadPool:创建一个定长的线程池,支持定时、周期性的任务执行","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Executors.newSingleThreadExecutor: 创建一个单线程化的线程池,使用一个唯一的工作线程执行任务,保证所有任务按照指定顺序(先入先出或者优先级)执行","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Executors.newSingleThreadScheduledExecutor:创建一个单线程化的线程池,支持定时、周期性的任务执行","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Executors.newWorkStealingPool:创建一个具有并行级别的work-stealing线程池","attrs":{}}]}]}],"attrs":{}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"其中,Executors.newWorkStealingPool方法是Java 8中新增的创建线程池的方法,它能够为线程池设置并行级别,具有更高的并发度和性能。除了此方法外,其他创建线程池的方法本质上调用的是ThreadPoolExecutor类的构造方法。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"例如,我们可以使用如下代码创建线程池。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"Executors.newWorkStealingPool();\nExecutors.newCachedThreadPool();\nExecutors.newScheduledThreadPool(3);\n","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"使用ThreadPoolExecutor类创建线程池","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"从代码结构上看ThreadPoolExecutor类继承自AbstractExecutorService,也就是说,ThreadPoolExecutor类具有AbstractExecutorService类的全部功能。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"既然Executors工具类中创建线程池大部分调用的都是ThreadPoolExecutor类的构造方法,所以,我们也可以直接调用ThreadPoolExecutor类的构造方法来创建线程池,而不再使用Executors工具类。接下来,我们一起看下ThreadPoolExecutor类的构造方法。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"ThreadPoolExecutor类中的所有构造方法如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public ThreadPoolExecutor(int corePoolSize,\n int maximumPoolSize,\n long keepAliveTime,\n TimeUnit unit,\n BlockingQueue workQueue) {\n this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,\n Executors.defaultThreadFactory(), defaultHandler);\n}\n\npublic ThreadPoolExecutor(int corePoolSize,\n int maximumPoolSize,\n long keepAliveTime,\n TimeUnit unit,\n BlockingQueue workQueue,\n ThreadFactory threadFactory) {\nthis(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,\n threadFactory, defaultHandler);\n}\n\npublic ThreadPoolExecutor(int corePoolSize,\n int maximumPoolSize,\n long keepAliveTime,\n TimeUnit unit,\n BlockingQueue workQueue,\n RejectedExecutionHandler handler) {\nthis(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,\n Executors.defaultThreadFactory(), handler);\n}\n\npublic ThreadPoolExecutor(int corePoolSize,\n int maximumPoolSize,\n long keepAliveTime,\n TimeUnit unit,\n BlockingQueue workQueue,\n ThreadFactory threadFactory,\n RejectedExecutionHandler handler) {\n if (corePoolSize < 0 ||\n maximumPoolSize <= 0 ||\n maximumPoolSize < corePoolSize ||\n keepAliveTime < 0)\n throw new IllegalArgumentException();\n if (workQueue == null || threadFactory == null || handler == null)\n throw new NullPointerException();\n this.acc = System.getSecurityManager() == null ?\n null :\n AccessController.getContext();\n this.corePoolSize = corePoolSize;\n this.maximumPoolSize = maximumPoolSize;\n this.workQueue = workQueue;\n this.keepAliveTime = unit.toNanos(keepAliveTime);\n this.threadFactory = threadFactory;\n this.handler = handler;\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"由ThreadPoolExecutor类的构造方法的源代码可知,创建线程池最终调用的构造方法如下。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,\n long keepAliveTime, TimeUnit unit,\n BlockingQueue workQueue,\n ThreadFactory threadFactory,\n RejectedExecutionHandler handler) {\n if (corePoolSize < 0 ||\n maximumPoolSize <= 0 ||\n maximumPoolSize < corePoolSize ||\n keepAliveTime < 0)\n throw new IllegalArgumentException();\n if (workQueue == null || threadFactory == null || handler == null)\n throw new NullPointerException();\n this.acc = System.getSecurityManager() == null ?\n null :\n AccessController.getContext();\n this.corePoolSize = corePoolSize;\n this.maximumPoolSize = maximumPoolSize;\n this.workQueue = workQueue;\n this.keepAliveTime = unit.toNanos(keepAliveTime);\n this.threadFactory = threadFactory;\n this.handler = handler;\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"关于此构造方法中各参数的含义和作用,各位可以移步《","attrs":{}},{"type":"link","attrs":{"href":"https://blog.csdn.net/l1028386804/article/details/104409796","title":"","type":null},"content":[{"type":"text","text":"高并发之——不得不说的线程池与ThreadPoolExecutor类浅析","attrs":{}}]},{"type":"text","text":"》进行查阅。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"大家可以自行调用ThreadPoolExecutor类的构造方法来创建线程池。例如,我们可以使用如下形式创建线程池。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"new ThreadPoolExecutor(0, Integer.MAX_VALUE,\n 60L, TimeUnit.SECONDS,\n new SynchronousQueue());\n","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"使用ForkJoinPool类创建线程池","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在Java8的Executors工具类中,新增了如下创建线程池的方式。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public static ExecutorService newWorkStealingPool(int parallelism) {\n return new ForkJoinPool\n (parallelism,\n ForkJoinPool.defaultForkJoinWorkerThreadFactory,\n null, true);\n}\n\npublic static ExecutorService newWorkStealingPool() {\n return new ForkJoinPool\n (Runtime.getRuntime().availableProcessors(),\n ForkJoinPool.defaultForkJoinWorkerThreadFactory,\n null, true);\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"从源代码可以可以,本质上调用的是ForkJoinPool类的构造方法类创建线程池,而从代码结构上来看ForkJoinPool类继承自AbstractExecutorService抽象类。接下来,我们看下ForkJoinPool类的构造方法。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public ForkJoinPool() {\n this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),\n defaultForkJoinWorkerThreadFactory, null, false);\n}\n public ForkJoinPool(int parallelism) {\n this(parallelism, defaultForkJoinWorkerThreadFactory, null, false);\n}\n\npublic ForkJoinPool(int parallelism,\n ForkJoinWorkerThreadFactory factory,\n UncaughtExceptionHandler handler,\n boolean asyncMode) {\n this(checkParallelism(parallelism),\n checkFactory(factory),\n handler,\n asyncMode ? FIFO_QUEUE : LIFO_QUEUE,\n \"ForkJoinPool-\" + nextPoolId() + \"-worker-\");\n checkPermission();\n}\n\nprivate ForkJoinPool(int parallelism,\n ForkJoinWorkerThreadFactory factory,\n UncaughtExceptionHandler handler,\n int mode,\n String workerNamePrefix) {\n this.workerNamePrefix = workerNamePrefix;\n this.factory = factory;\n this.ueh = handler;\n this.config = (parallelism & SMASK) | mode;\n long np = (long)(-parallelism); // offset ctl counts\n this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过查看源代码得知,ForkJoinPool的构造方法,最终调用的是如下私有构造方法。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"private ForkJoinPool(int parallelism,\n ForkJoinWorkerThreadFactory factory,\n UncaughtExceptionHandler handler,\n int mode,\n String workerNamePrefix) {\n this.workerNamePrefix = workerNamePrefix;\n this.factory = factory;\n this.ueh = handler;\n this.config = (parallelism & SMASK) | mode;\n long np = (long)(-parallelism); // offset ctl counts\n this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"其中,各参数的含义如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"parallelism:并发级别。","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"factory:创建线程的工厂类对象。","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"handler:当线程池中的线程抛出未捕获的异常时,统一使用UncaughtExceptionHandler对象处理。","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"mode:取值为FIFO_QUEUE或者LIFO_QUEUE。","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"workerNamePrefix:执行任务的线程名称的前缀。","attrs":{}}]}]}],"attrs":{}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"当然,私有构造方法虽然是参数最多的一个方法,但是其不会直接对外方法,我们可以使用如下方式创建线程池。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"new ForkJoinPool();\nnew ForkJoinPool(Runtime.getRuntime().availableProcessors());\nnew ForkJoinPool(Runtime.getRuntime().availableProcessors(),\n ForkJoinPool.defaultForkJoinWorkerThreadFactory,\n null, true);\n","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"使用ScheduledThreadPoolExecutor类创建线程池","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在Executors工具类中存在如下方法类创建线程池。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public static ScheduledExecutorService newSingleThreadScheduledExecutor() {\n return new DelegatedScheduledExecutorService\n (new ScheduledThreadPoolExecutor(1));\n}\n\npublic static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {\n return new DelegatedScheduledExecutorService\n (new ScheduledThreadPoolExecutor(1, threadFactory));\n}\n\npublic static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {\n return new ScheduledThreadPoolExecutor(corePoolSize);\n}\n\npublic static ScheduledExecutorService newScheduledThreadPool(\n int corePoolSize, ThreadFactory threadFactory) {\n return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"从源码来看,这几个方法本质上调用的都是ScheduledThreadPoolExecutor类的构造方法,ScheduledThreadPoolExecutor中存在的构造方法如下所示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public ScheduledThreadPoolExecutor(int corePoolSize) {\n super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,\n new DelayedWorkQueue());\n}\n\npublic ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) {\n super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,\n new DelayedWorkQueue(), threadFactory);\n}\n\npublic ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler) {\n super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,\n new DelayedWorkQueue(), handler);\n}\n\npublic ScheduledThreadPoolExecutor(int corePoolSize,ThreadFactory threadFactory, RejectedExecutionHandler handler) {\n super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,\n new DelayedWorkQueue(), threadFactory, handler);\n}\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"而从代码结构上看,ScheduledThreadPoolExecutor类继承自ThreadPoolExecutor类,本质上还是调用ThreadPoolExecutor类的构造方法,只不过此时传递的队列为DelayedWorkQueue。我们可以直接调用ScheduledThreadPoolExecutor类的构造方法来创建线程池,例如以如下形式创建线程池。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"new ScheduledThreadPoolExecutor(3)\n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"好了,今天就到这儿吧,我是冰河,我们下期见~~","attrs":{}}]}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章