JDK提供的幾種線程池比較

JDK提供的幾種線程池緩存

newFixedThreadPool
建立一個指定工做線程數量的線程池。每當提交一個任務就建立一個工做線程,若是工做線程數量達到線程池初始的最大數,則將提交的任務存入到池隊列中。app

newCachedThreadPool
建立一個可緩存的線程池。這種類型的線程池特色是:
1).工做線程的建立數量幾乎沒有限制(其實也有限制的,數目爲Interger. MAX_VALUE), 這樣可靈活的往線程池中添加線程。
2).若是長時間沒有往線程池中提交任務,即若是工做線程空閒了指定的時間(默認爲1分鐘),則該工做線程將自動終止。終止後,若是你又提交了新的任務,則線程池從新建立一個工做線程。ui

newSingleThreadExecutor
建立一個單線程化的Executor,即只建立惟一的工做者線程來執行任務,若是這個線程異常結束,會有另外一個取代它,保證順序執行(我以爲這點是它的特點)。單工做線程最大的特色是可保證順序地執行各個任務,而且在任意給定的時間不會有多個線程是活動的 。this

newScheduleThreadPool
建立一個定長的線程池,並且支持定時的以及週期性的任務執行,相似於Timer。(這種線程池原理暫還沒徹底瞭解透徹).net

總結:
FixedThreadPool
是一個典型且優秀的線程池,它具備線程池提升程序效率和節省建立線程時所耗的開銷的優勢。可是,在線程池空閒時,即線程池中沒有可運行任務時,它不會釋放工做線程,還會佔用必定的系統資源。線程

CachedThreadPool
特色是在線程池空閒時,即線程池中沒有可運行任務時,它會釋放工做線程,從而釋放工做線程所佔用的資源。可是,但當出現新任務時,又要建立一新的工做線程,又要必定的系統開銷。而且,在使用CachedThreadPool時,必定要注意控制任務的數量,不然,因爲大量線程同時運行,頗有會形成系統癱瘓。orm


線程池工廠類:
Executors
Factory and utility methods for {@link Executor}, {@link ExecutorService}, {@link ScheduledExecutorService}, {@link ThreadFactory}, and {@link Callable} classes defined in this package. This class supports the following kinds of methods:
Methods that create and return an {@link ExecutorService} set up with commonly useful configuration settings.
Methods that create and return a {@link ScheduledExecutorService} set up with commonly useful configuration settings.
Methods that create and return a "wrapped" ExecutorService, that disables reconfiguration by making implementation-specific methods inaccessible.
Methods that create and return a {@link ThreadFactory} that sets newly created threads to a known state.
Methods that create and return a {@link Callable} out of other closure-like forms, so they can be used in execution methods requiring <tt>Callable</tt>.blog

 

轉自:http://blog.csdn.net/it_man/article/details/7193727隊列

相關文章
相關標籤/搜索