转载

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

系统预定了几个线程池,不过建议手动创建,以防止错误创建消耗资源,比如创建太多线程或者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);
    }
}

运行结果如下:

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

原文  https://segmentfault.com/a/1190000019933783
正文到此结束
Loading...