【高併發】從源碼角度分析創建線程池究竟有哪些方式

{"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":{}}]}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章