// 创建可以容纳3个线程的线程池
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, //core pool size
nThreads, //maximum pool size
0L, //keep alive time
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
CachedThreadPool会创建一个缓存区,将初始化的线程缓存起来。会终止并且从缓存中移除已有60秒未被使用的线程。
如果线程有可用的,就使用之前创建好的线程,
如果线程没有可用的,就新创建线程。
任务是交替执行的
// 线程池的大小会根据执行的任务数动态分配
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, //core pool size
Integer.MAX_VALUE, //maximum pool size
60L, //keep alive time
TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
// 创建单个线程的线程池,如果当前线程在执行任务时突然中断,则会创建一个新的线程替代它继续执行任务
ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, //core pool size
1, //maximum pool size
0L, //keep alive time
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
// 效果类似于Timer定时器
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, //core pool size
Integer.MAX_VALUE, //maximum pool size
0, //keep alive time
TimeUnit.NANOSECONDS,
new DelayedWorkQueue());
}
数据来源
http://blog.csdn.net/vking_wang/article/details/9619137
在FixedThreadPool中,有一个固定大小的池。
如果当前需要执行的任务超过池大小,那么多出的任务处于等待状态,直到有空闲下来的线程执行任务,
如果当前需要执行的任务小于池大小,空闲的线程也不会去销毁。
原文:http://www.cnblogs.com/hualuoshuijia/p/6915628.html