這篇文章主要講解了“線程池ThreadPoolExecutor有什么作用”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“線程池ThreadPoolExecutor有什么作用”吧!
一、初始化線程池(4種):
1、newFixedThreadPool()
public final static ExecutorService esPool = Execustor.newFixedThreadPool(50);
特點:corePoolSize == maxPoolSize,使用LinkedBlockingQueue作為堵塞隊列;沒有可執行任務時不會釋放線程池;
2、newCachedThreadPool()
public final static ExecutorService esPool = Execustor.newCachedThreadPool();
特點:默認緩存60s,線程數可以達到Integer.MAX_VALUE,內部使用SynchronousQueue作為堵塞隊列;沒有可執行任務時,達到keepAliveTime會釋放線程資源,新任務沒有執行空閑線程就得重新創建新的線程,會導致系統開銷;使用時,注意控制并發數,減少創建新線程數;
3、newScheduleThreadPool()
public final static ExecutorService esPool = Execustor.newScheduleThreadPool(50);
特點:指定時間內周期性內執行所提交的任務,一般用于定時同步數據;
4、newSingleThreadExecutor()
特點:初始化只有一個線程的線程池;內部使用LinkedBlockingQueue作為堵塞隊列;
二、源碼實現:
1、ThreadPoolExecutor構造器
public ThreadPoolExecutor( int corePoolSize,//核心線程數 int maximumPoolSize,//最大線程數 long keepAliveTime,//線程存活時間(必須在線程數在corePoolSize與maximumPoolSie之間時,存活時間才能生效) TimeUnit unit,//存活時間的單位 BlockingQueue<Runnable> workQueue,//堵塞隊列 RejectedExecutionHandler handler//當拒絕處理任務時的策略 ) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler); }
說明:堵塞隊列BlockingQueue:1)ArrayBlockingQueue(數組結構的界限堵塞隊列,FIFO);2)LinkedBlockQueue(鏈表結構的堵塞隊列,FIFO);3)SynchronousQueue(不存儲元素的堵塞隊列,每次插入必須等到另一個線程移除);4)PriorityBlockingQueue(具有優先級的堵塞隊列)。
拒絕處理任務的策略RejectedExecutionHandler :1)、ThreadPoolExecutor.AbortPolicy(拋棄當前線程,并拋出RejectedExecutionException異常)2)、ThreadPoolExecutor.DiscardPolicy(拋棄當前線程,不拋出異常);3)、ThreadPoolExecutor.DiscardOldestPolicy(拋棄最前面的任務,然后重新嘗試此執行過程);4)、CallerRunnsPolicy(調用線程執行此任務)
2、execute()
public void execute(Runnable command) { if (command == null) throw new NullPointerException(); int c = ctl.get(); //獲取當前線程的數量:workerCountOf() if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true))//當當前線程數量小于corePoolSize時,就addWorker return; c = ctl.get(); } //如果當前線程處于Running狀態; if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); //檢查線程池(因為可能在上次檢查后,有線程資源被釋放),是否有空閑的線程 if (! isRunning(recheck) && remove(command)) reject(command); else if (workerCountOf(recheck) == 0) addWorker(null, false); } //如果當前線程處于非Running狀態; else if (!addWorker(command, false)) reject(command); }
3、reject()
final void reject(Runnable command) { handler.rejectedExecution(command, this); }
4、submit()
public <T> Future<T> submit(Callable<T> task) { if (task == null) throw new NullPointerException(); //封裝成一個FutureTask對象,FutureTask類實現Runnable接口 RunnableFuture<T> ftask = newTaskFor(task); //執行execute(),通過execute提交到FutureTask線程池中等待被執行,最終執行FutureTask的run方法 execute(ftask); return ftask; } protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { return new FutureTask<T>(callable); }
5、線程狀態
private static final int COUNT_BITS = Integer.SIZE - 3; //即高3位為111,該狀態的線程池會接收新任務,并處理阻塞隊列中的任務; private static final int RUNNING = -1 << COUNT_BITS; //即高3位為000,該狀態的線程池不會接收新任務,但會處理阻塞隊列中的任務; private static final int SHUTDOWN = 0 << COUNT_BITS; //即高3位為001,該狀態的線程不會接收新任務,也不會處理阻塞隊列中的任務,而且會中斷正在運行的任務; private static final int STOP = 1 << COUNT_BITS; //即高3位為010,該狀態表示線程池對線程進行整理優化; private static final int TIDYING = 2 << COUNT_BITS; //即高3位為011,該狀態表示線程池停止工作; private static final int TERMINATED = 3 << COUNT_BITS;
6、runWorker()(真正執行任務的接口)
final void runWorker(Worker w) { Thread wt = Thread.currentThread(); Runnable task = w.firstTask; w.firstTask = null; w.unlock(); // allow interrupts boolean completedAbruptly = true; try { while (task != null || (task = getTask()) != null) { w.lock(); // If pool is stopping, ensure thread is interrupted; // if not, ensure thread is not interrupted. This // requires a recheck in second case to deal with // shutdownNow race while clearing interrupt if ((runStateAtLeast(ctl.get(), STOP) || (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP))) && !wt.isInterrupted()) wt.interrupt(); try { beforeExecute(wt, task); Throwable thrown = null; try { task.run(); } catch (RuntimeException x) { thrown = x; throw x; } catch (Error x) { thrown = x; throw x; } catch (Throwable x) { thrown = x; throw new Error(x); } finally { afterExecute(task, thrown);//啥都沒做 } } finally { task = null; w.completedTasks++; w.unlock(); } } completedAbruptly = false; } finally { processWorkerExit(w, completedAbruptly); } } protected void afterExecute(Runnable r, Throwable t) { }
感謝各位的閱讀,以上就是“線程池ThreadPoolExecutor有什么作用”的內容了,經過本文的學習后,相信大家對線程池ThreadPoolExecutor有什么作用這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。