JDK提供的几种线程池比较

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

posted @ 2015-09-14 13:50  沐风山  阅读(5360)  评论(0编辑  收藏  举报