java并发编程学习之线程池预定义线程池四

33次阅读

共计 1520 个字符,预计需要花费 4 分钟才能阅读完成。

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

FixedThreadPool

固定线程数量,无界队列

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

SingleThreadExecutor

固定线程数量,数量为 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);
    }
}

运行结果如下:

正文完
 0