如果在使用執行緒的時候就去建立乙個新執行緒, 當併發的執行緒數量很多, 並且每個執行緒都是執行乙個時間很短的任務就結束了, 系統在建立和銷毀執行緒上花費的時間和消耗的系統資源都相當大, 甚至要比處理任務的時間和資源要多的多, 同時活動的執行緒也需要消耗系統資源.executor是乙個頂層介面, 它只宣告了乙個方法 execute(runnable), 返回值 void, 字面上就是用來執行傳進去的任務的具體的介紹不多說, 在別的部落格已經有很詳細的介紹比如executorservice介面繼承了executor 介面, 並宣告了一些方法 submit, invokeall, invokeany, shoutdown, shoutdownnow等
抽象類abstractexecutorservice實現了 executorservice 介面, 基本實現了 executorservice 中宣告的所有方法
threadpoolexecutor繼承了抽象類abstractexecutorservice
寫的很好(有錯誤地方)executors靜態工廠雖然提供了幾種建立常用執行緒池方法, 但是不建議慎用 executors 去建立, 而是通過 threadpoolexecutor 的方式, 可以更加明確執行緒池的執行規則, 避免系統資源耗盡的風險executors 各個方法的弊端:newfixedthreadpool 和 newsinglethreadexecutor:
主要問題是堆積的請求處理佇列可能會耗費非常大的記憶體
newcachedthreadpool 和 newscheduledthreadpool:
主要問題是執行緒數最大數是 integer.max_value, 可能會建立數量非常多的執行緒
// org.apache.commons.lang3.concurrent.basicthreadfactory
new scheduledthreadpoolexecutor(1,
new basicthreadfactory.builder().namingpattern("example-schedule-pool-%d").daemon(true).build());
待更新…threadfactory namedthreadfactory = new threadfactorybuilder().setnameformat("demo-pool-%d").build();
threadpoolexecutor pool =
new threadpoolexecutor(5, 200, 0l, timeunit.milliseconds, new linkedblockingqueue(1024),
namedthreadfactory, new threadpoolexecutor.abortpolicy());
pool.execute(() -> );
執行緒池的使用
簡而言之 兩個類 執行緒池的 類 public class threadpoolproxyfactory return mnormalthreadpoolproxy return public static threadpoolproxy createdownloadthreadpoolproxy ...
執行緒池的使用
執行緒池能幫助我們有效的管理執行緒,避免重複的建立銷毀執行緒。newfixedthreadpool 固定執行緒數量的執行緒池 newsinglethreadexecutor 返回乙個只有乙個執行緒的執行緒池 newcachedthreadpool 返回乙個可根據實際情況調整執行緒數量的執行緒池 ne...
執行緒池的使用
runnable介面 通常,執行緒池都是通過執行緒池工廠建立,再呼叫執行緒池中的方法獲取執行緒,再通過執行緒去執行任務方法。使用執行緒池中線程物件的步驟 建立執行緒池物件 建立runnable介面子類物件 提交runnable介面子類物件 關閉執行緒池 public class threadpool...