1、CachedThreadPool简介
CachedThreadPool
是无核心线程,非核心线程数量无限,执行完闲置 60s 后回收,任务队列为不存储元素的阻塞队列。一般是用在执行大量耗时少的任务的使用场景。相对于通过使用 ThreadPoolExecutor
的方式,使用CachedThreadPool
更方便,有些参数可能不需要设置,可以根据实现情况使用。
2、newCachedThreadPool源码
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
3、使用示例
import java.util.concurrent.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
// 需执行的任务
Runnable task =new Runnable(){
public void run() {
Date date=new Date();
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(" 当前时间为:"+dateFormat.format(date));
}
};
//添加任务
cachedThreadPool.execute(task);
cachedThreadPool.awaitTermination(10000, TimeUnit.MILLISECONDS);
System.exit(0); //success
}
}