您好,登錄后才能下訂單哦!
這篇文章主要講解了“線程池ThreadPoolExecutor有什么作用”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“線程池ThreadPoolExecutor有什么作用”吧!
一、初始化線程池(4種):
1、newFixedThreadPool()
public final static ExecutorService esPool = Execustor.newFixedThreadPool(50);
特點:corePoolSize == maxPoolSize,使用LinkedBlockingQueue作為堵塞隊列;沒有可執(zhí)行任務時不會釋放線程池;
2、newCachedThreadPool()
public final static ExecutorService esPool = Execustor.newCachedThreadPool();
特點:默認緩存60s,線程數(shù)可以達到Integer.MAX_VALUE,內部使用SynchronousQueue作為堵塞隊列;沒有可執(zhí)行任務時,達到keepAliveTime會釋放線程資源,新任務沒有執(zhí)行空閑線程就得重新創(chuàng)建新的線程,會導致系統(tǒng)開銷;使用時,注意控制并發(fā)數(shù),減少創(chuàng)建新線程數(shù);
3、newScheduleThreadPool()
public final static ExecutorService esPool = Execustor.newScheduleThreadPool(50);
特點:指定時間內周期性內執(zhí)行所提交的任務,一般用于定時同步數(shù)據(jù);
4、newSingleThreadExecutor()
特點:初始化只有一個線程的線程池;內部使用LinkedBlockingQueue作為堵塞隊列;
二、源碼實現(xiàn):
1、ThreadPoolExecutor構造器
public ThreadPoolExecutor( int corePoolSize,//核心線程數(shù) int maximumPoolSize,//最大線程數(shù) long keepAliveTime,//線程存活時間(必須在線程數(shù)在corePoolSize與maximumPoolSie之間時,存活時間才能生效) TimeUnit unit,//存活時間的單位 BlockingQueue<Runnable> workQueue,//堵塞隊列 RejectedExecutionHandler handler//當拒絕處理任務時的策略 ) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler); }
說明:堵塞隊列BlockingQueue:1)ArrayBlockingQueue(數(shù)組結構的界限堵塞隊列,F(xiàn)IFO);2)LinkedBlockQueue(鏈表結構的堵塞隊列,F(xiàn)IFO);3)SynchronousQueue(不存儲元素的堵塞隊列,每次插入必須等到另一個線程移除);4)PriorityBlockingQueue(具有優(yōu)先級的堵塞隊列)。
拒絕處理任務的策略RejectedExecutionHandler :1)、ThreadPoolExecutor.AbortPolicy(拋棄當前線程,并拋出RejectedExecutionException異常)2)、ThreadPoolExecutor.DiscardPolicy(拋棄當前線程,不拋出異常);3)、ThreadPoolExecutor.DiscardOldestPolicy(拋棄最前面的任務,然后重新嘗試此執(zhí)行過程);4)、CallerRunnsPolicy(調用線程執(zhí)行此任務)
2、execute()
public void execute(Runnable command) { if (command == null) throw new NullPointerException(); int c = ctl.get(); //獲取當前線程的數(shù)量:workerCountOf() if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true))//當當前線程數(shù)量小于corePoolSize時,就addWorker return; c = ctl.get(); } //如果當前線程處于Running狀態(tài); 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狀態(tài); 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對象,F(xiàn)utureTask類實現(xiàn)Runnable接口 RunnableFuture<T> ftask = newTaskFor(task); //執(zhí)行execute(),通過execute提交到FutureTask線程池中等待被執(zhí)行,最終執(zhí)行FutureTask的run方法 execute(ftask); return ftask; } protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { return new FutureTask<T>(callable); }
5、線程狀態(tài)
private static final int COUNT_BITS = Integer.SIZE - 3; //即高3位為111,該狀態(tài)的線程池會接收新任務,并處理阻塞隊列中的任務; private static final int RUNNING = -1 << COUNT_BITS; //即高3位為000,該狀態(tài)的線程池不會接收新任務,但會處理阻塞隊列中的任務; private static final int SHUTDOWN = 0 << COUNT_BITS; //即高3位為001,該狀態(tài)的線程不會接收新任務,也不會處理阻塞隊列中的任務,而且會中斷正在運行的任務; private static final int STOP = 1 << COUNT_BITS; //即高3位為010,該狀態(tài)表示線程池對線程進行整理優(yōu)化; private static final int TIDYING = 2 << COUNT_BITS; //即高3位為011,該狀態(tài)表示線程池停止工作; private static final int TERMINATED = 3 << COUNT_BITS;
6、runWorker()(真正執(zhí)行任務的接口)
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有什么作用”的內容了,經(jīng)過本文的學習后,相信大家對線程池ThreadPoolExecutor有什么作用這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。