一、newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
1.是一个可以无限扩大的线程池;
2.比较适合处理执行时间比较小的任务;
3.corePoolSize为0,maximumPoolSize为无限大,线程数量可以无限大;
4.keepAliveTime为60S,线程空闲时间超过60S就会被杀死;
5.采用SynchronousQueue装等待的任务,这个阻塞队列没有存储空间,这意味着只要有请求到来,就必须要找到一条工作线程处理他,如果当前没有空闲的线程,那么就会再创建一条新的线程。
二、newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
1.固定大小的线程池nThreads;
2.corePoolSize和maximunPoolSize都为用户设定的线程数量nThreads;
3.keepAliveTime为0,一旦有多余的空闲线程,就会被立即停止掉;但这里keepAliveTime无效(由于采用了无界队列);
4.阻塞队列采用了LinkedBlockingQueue,一个无界队列;由于阻塞队列是一个无界队列,因此永远不可能拒绝任务;由于采用了无界队列,实际线程数量将永远维持在nThreads,因此maximumPoolSize和keepAliveTime将无效。
三、ScheduledThreadPool
它用来处理延时任务或定时任务。
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(40);
scheduled.scheduleAtFixedRate(new Runnable() {
int i = 0;
@Override
public void run() {
i++;
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}, 0, 100, TimeUnit.MILLISECONDS);// 0表示首次执行任务的延迟时间,40表示每次执行任务的间隔时间,TimeUnit.MILLISECONDS执行的时间间隔数值单位
四、newSingleThreadExecutor
Executors.newSingleThreadExecutor()返回一个线程池(这个线程池只有一个线程),这个线程池可以在线程死后(或发生异常时)重新启动一个线程来替代原来的线程继续执行下去!