Java多线程和线程池的两个问题-1

一、前提
1、
最近在研究线程池,在网上找到创建线程池的方法和线程池的类型,然后实现起来是这样的。

    ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); // 带缓存的线程池

    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); // 固定长度的线程池,最大线程数=核心线程数

    ExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3); // 固定长度的线程池,支持定时及周期性任务执行。

    ExecutorService singleThreadPool = Executors.newSingleThreadExecutor(); // 单核线程

2、
其中,和定时任务相关的那个线程池我有点兴趣,但是按上述的方法创建完线程池以后,找不到相关的方法可以传入延时的时间。后来在网上查了下,如果要实现延时执行任务的话,要用另外一种方法:

    TicketThread ticketThread1 = new TicketThread();

    ScheduledExecutorService service = new ScheduledThreadPoolExecutor(4);

    service.schedule(ticketThread1, 20, TimeUnit.SECONDS);

二、问题
1、请问

ExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);

ScheduledExecutorService scheduledService = new ScheduledThreadPoolExecutor(3);

这两种方式有什么不一样,第一种方式创建出来的线程池要怎么实现延时工作呢?如果不行,哪些场景会用到这种线程池?

2、根据第二种创建方法,我怀疑4种线程池都有类似的创建方法(比如:

FixedExecutorService fixedService = new FixedThreadPoolExecutor(3);


。但试了一下,似乎只有延时的可以这样创建,想确认下是否真的是这样?还是我有遗漏?

请大神指教,谢谢!

阅读 1.9k
2 个回答

推荐使用 new ThreadPoolExecutor()这种方式,你能够明白具体参数的意义。等用得熟练了之后在考虑使用executors来创建,不然明显坏处更大,阿里巴巴的规范上也说,禁止使用executors来创建。可能很多人根本就不理解其意义就跟风使用。至于你的问题

/**
     * Creates a thread pool that can schedule commands to run after a
     * given delay, or to execute periodically.
     * @param corePoolSize the number of threads to keep in the pool,
     * even if they are idle
     * @return a newly created scheduled thread pool
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
     */
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }

没有任何差别

多态了解下。
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题