Java线程池深入理解
生活随笔
收集整理的這篇文章主要介紹了
Java线程池深入理解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近項目中進行告警模塊性能優化,不少地方使用了線程池技術,整理總結如下。
package com.coshaho.threadpool;import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;/*** 線程池學習* @author coshaho*/ public class MyThreadPool {/*** 第一章 線程池初始化*/// 核心線程數量private int corePoolSize;// 最大線程數量private int maximumPoolSize;// 空閑線程存活時間private long keepAliveTime;// 空閑線程存活時間單位private TimeUnit unit;// 線程阻塞隊列private BlockingQueue<Runnable> workQueue;/*** 線程創建工廠,一般自定義,用于封裝傳入ThreadPool的Runnable任務* 默認:Executors.defaultThreadFactory()* public interface ThreadFactory { * Thread newThread(Runnable r); * }*/private ThreadFactory threadFactory;// 線程拒絕機制private RejectedExecutionHandler handler;public void initThreadPoolExecutor(){ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit,workQueue,threadFactory,handler);// 設置線程池核心線程數executor.setCorePoolSize(corePoolSize);// 設置線程池最大線程數executor.setMaximumPoolSize(maximumPoolSize);// 初始化一個核心線程executor.prestartCoreThread();// 初始化所有核心線程executor.prestartAllCoreThreads();// 不會立即終止線程池,而是要等所有任務緩存隊列中的任務都執行完后才終止,但再也不會接受新的任務executor.shutdown();// 立即終止線程池,嘗試打斷正在執行的任務,并且清空任務緩存隊列,返回尚未執行的任務executor.shutdownNow();}/*** 第二章 線程池任務處理機制* 來了一個任務后的處理機制* 1、 當線程池線程數量小于corePoolSize時,立即新建一個線程執行任務;* 2、 當線程池線程數量等于corePoolSize,workQueue不滿時,任務入workQueue隊列,等待調度;* 3、 當workQueue滿,線程池線程數量小于maximumPoolSize時,新建線程執行任務;* 4、 當線程池線程數量等于maximumPoolSize,workQueue滿時,采用線程拒絕機制處理任務。*//*** 第三章 線程阻塞隊列* workQueue的類型為BlockingQueue<Runnable>,通常可以取下面三種類型:* 1、ArrayBlockingQueue:基于數組的先進先出隊列,此隊列創建時必須指定大小;* 2、LinkedBlockingQueue:基于鏈表的先進先出隊列,如果創建時沒有指定此隊列大小,則默認為Integer.MAX_VALUE;* 3、synchronousQueue:這個隊列比較特殊,它不會保存提交的任務,而是將直接新建一個線程來執行新來的任務。*//*** 第四章 線程拒絕機制*/public void rejectedExecutionHandlerLearn(){// 丟棄任務并拋出RejectedExecutionException異常handler = new ThreadPoolExecutor.AbortPolicy();// 也是丟棄任務,但是不拋出異常handler = new ThreadPoolExecutor.DiscardPolicy();// 丟棄隊列最前面的任務,然后重新嘗試執行任務(重復此過程)handler = new ThreadPoolExecutor.DiscardOldestPolicy();// 由調用線程處理該任務 handler = new ThreadPoolExecutor.CallerRunsPolicy();}/*** 第五章 JDK默認線程池*/public void jdkThreadPool(){//創建一個緩沖池,緩沖池容量大小為Integer.MAX_VALUEExecutors.newCachedThreadPool(); //創建容量為1的緩沖池Executors.newSingleThreadExecutor();//創建固定容量大小的緩沖池 Executors.newFixedThreadPool(5); }/**public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));}public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());}*//*** 第六章 線程池大小設置* 1、 如果是CPU密集型任務,就需要盡量壓榨CPU,參考值可以設為 NCPU+1;* 2、 如果是IO密集型任務,參考值可以設置為2*NCPU。*//*** 第七章 JDK源碼* Creates a new {@code ThreadPoolExecutor} with the given initial* parameters.** @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* @throws IllegalArgumentException if one of the following holds:<br>* {@code corePoolSize < 0}<br>* {@code keepAliveTime < 0}<br>* {@code maximumPoolSize <= 0}<br>* {@code maximumPoolSize < corePoolSize}* @throws NullPointerException if {@code workQueue}* or {@code threadFactory} or {@code handler} is nullpublic ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler)*/ }?
轉載于:https://www.cnblogs.com/coshaho/p/5426887.html
總結
以上是生活随笔為你收集整理的Java线程池深入理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 增删改查的45道题
- 下一篇: Jmeter报告优化之New XSL s