JDK提供的幾種線程池
newFixedThreadPool
創建一個指定工作線程數量的線程池。每當提交一個任務就創建一個工作線程,如果工作線程數量達到線程池初始的最大數,則將提交的任務存入到池隊列中。
newCachedThreadPool
創建一個可緩存的線程池。這種類型的線程池特點是:
1).工作線程的創建數量幾乎沒有限制(其實也有限制的,數目為Interger. MAX_VALUE), 這樣可靈活的往線程池中添加線程。
2).如果長時間沒有往線程池中提交任務,即如果工作線程空閑了指定的時間(默認為1分鍾),則該工作線程將自動終止。終止后,如果你又提交了新的任務,則線程池重新創建一個工作線程。
newSingleThreadExecutor
創建一個單線程化的Executor,即只創建唯一的工作者線程來執行任務,如果這個線程異常結束,會有另一個取代它,保證順序執行(我覺得這點是它的特色)。單工作線程最大的特點是可保證順序地執行各個任務,並且在任意給定的時間不會有多個線程是活動的 。
newScheduleThreadPool
創建一個定長的線程池,而且支持定時的以及周期性的任務執行,類似於Timer。(這種線程池原理暫還沒完全了解透徹)
總結:
FixedThreadPool
是一個典型且優秀的線程池,它具有線程池提高程序效率和節省創建線程時所耗的開銷的優點。但是,在線程池空閑時,即線程池中沒有可運行任務時,它不會釋放工作線程,還會占用一定的系統資源。
CachedThreadPool
特點是在線程池空閑時,即線程池中沒有可運行任務時,它會釋放工作線程,從而釋放工作線程所占用的資源。但是,但當出現新任務時,又要創建一新的工作線程,又要一定的系統開銷。並且,在使用CachedThreadPool時,一定要注意控制任務的數量,否則,由於大量線程同時運行,很有會造成系統癱瘓。
線程池工廠類:
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>.
轉自:http://blog.csdn.net/it_man/article/details/7193727