Java线程工具类Executors四种线程池

1.newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

public static ExecutorService newCachedThreadPool() {

    return new ThreadPoolExecutor(0,//核心线程数为零

                                                         Integer.MAX_VALUE, //线程非核心数为MAX_VALUE =0x7fffffff(int最大值2147483647)

                                                         60L, //空闲线程存活时间

                                                        TimeUnit.SECONDS,//时间单位

                                                      new SynchronousQueue());//阻塞队列(SynchronousQueue内部没有任何存放元素的能力

}

2.newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

public static ExecutorService newFixedThreadPool(int nThreads) {

     return new ThreadPoolExecutor(nThreads,//核心线程数为零nThreads

                                                         nThreads,//线程非核心数为 nThreads/

                                                        0L, //没有过期时间

                                                        TimeUnit.MILLISECONDS,

                                                        new LinkedBlockingQueue());//链接队列默认长度为为MAX_VALUE =0x7fffffff(int最大值2147483647)

}

3newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

public static ExecutorService newSingleThreadExecutor() {

    return new FinalizableDelegatedExecutorService

                    (new ThreadPoolExecutor(1,//核心线程数为零1

                                                                1,//线程非核心数为 1

                                                                0L, //没有过期时间

                                                                TimeUnit.MILLISECONDS,

                                                                new LinkedBlockingQueue()));//链接队列默认长度为为MAX_VALUE =0x7fffffff

}

4.newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。

publicScheduledThreadPoolExecutor(int corePoolSize){super(corePoolSize,Integer.MAX_VALUE,0,NANOSECONDS,newDelayedWorkQueue());}

//核心线程数为零corePoolSize

//线程非核心数为MAX_VALUE =0x7fffffff(int最大值2147483647)

 //没有过期时间

//队列默认长度为16

主要是通过DelayedWorkQueue来实现的定时线程.

你可能感兴趣的:(Java线程工具类Executors四种线程池)