天天看点

线程池之-newCachedThreadPool

newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

package com.executor.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 作者:wx
 * @createDate 创建时间:Sep 16, 2019 2:44:27 PM
 */
public class CachedThreadPoolDemo {
	public static void main(String[] args) {
		ExecutorService executorService = Executors.newCachedThreadPool();
		for (int i = 0; i < 10; i++) {
			int temp = i;
			executorService.execute(new Runnable() {

				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName() + "," + temp);
				}
			});
		}
	}

}
           

运行结果为:

线程池之-newCachedThreadPool

如图只创建了7个线程,其中pool-1-thread-5,pool-1-thread-6,pool-1-thread-7这3个线程重复利用了2次。

总结: 线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。

继续阅读