开发手册 欢迎您!
软件开发者资料库

Java 线程池 CachedThreadPool的使用及示例代码

Java 线程池 CachedThreadPool是Executors封装好的4种常见的功能线程池之一,它是可缓存线程池,优先利用闲置线程处理新任务,线程池中线程数量可以无限大。本文主要介绍 CachedThreadPool的使用及示例代码。

1、CachedThreadPool简介

CachedThreadPool是无核心线程,非核心线程数量无限,执行完闲置 60s 后回收,任务队列为不存储元素的阻塞队列。一般是用在执行大量耗时少的任务的使用场景。相对于通过使用 ThreadPoolExecutor 的方式,使用CachedThreadPool更方便,有些参数可能不需要设置,可以根据实现情况使用。

2、newCachedThreadPool源码

public static ExecutorService newCachedThreadPool() {    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,                                  60L, TimeUnit.SECONDS,                                  new SynchronousQueue());}public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,                                  60L, TimeUnit.SECONDS,                                  new SynchronousQueue(),                                  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  }}