系统预定了几个线程池,不过建议手动创建,以防止错误创建消耗资源,比如创建太多线程或者OOM

FixedThreadPool

创建一个固定长度的线程池,每提交一个任务时就创建一个线程,知道达到线程池的最大数量。无界队列

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

SingleThreadExecutor

单线程的Executor,固定线程数量,数量为1,无界队列,会按顺序执行

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}

CachedThreadPool

不限制线程数量,使用SynchronousQueue队列,使用于短任务。任务增加时,创建新的线程,线程的数量不受限制。线程池的规模超过当前的处理请求,回收空闲的线程。

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

WorkStealingPool

基于ForkJoinPool

public static ExecutorService newWorkStealingPool(int parallelism) {
    return new ForkJoinPool
        (parallelism,
         ForkJoinPool.defaultForkJoinWorkerThreadFactory,
         null, true);
}

ScheduledThreadPoolExecutor

用于周期性执行任务

public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
    return new DelegatedScheduledExecutorService
        (new ScheduledThreadPoolExecutor(1));
}

示例

public class ScheduledDemo {
    static class Thread1 implements Runnable {
        @Override
        public void run() {
            SimpleDateFormat formater = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            System.out.println(Thread.currentThread().getName() + ":" + formater.format(new Date()));
        }
    }

    public static void main(String[] args) {
        ScheduledThreadPoolExecutor schedule
                = new ScheduledThreadPoolExecutor(1);
        //第一个是Runnable,第二个是第一次开始的时间,第三个是周期时间,第四个是时间单位
        schedule.scheduleAtFixedRate(new Thread1(),1000,1000, TimeUnit.MILLISECONDS);
    }
}

运行结果如下:

clipboard.png


大军
847 声望183 粉丝

学而不思则罔,思而不学则殆