线程池核心参数

线程池核心参数

    ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)

1)corePoolSize(线程池基本大小)

2)maximumPoolSize(线程池最大数量)

3)keepAliveTime(空闲线程活动保持时间):线程池工作线程空闲后,保持存活时间

4)TimeUnit(时间单位)

5)workQueue(任务队列):用于保存等待执行任务的阻塞队列
1、ArrayBlockQueue
2、LinkedBlockQueue
3、SynchronousQueue(不存储元素阻塞队列)
4、PriorityBlockingQueue(优先级无限阻塞队列)

6) threadFactory(线程工厂)

7) handler(饱和策略)
1、AbortPolicy:直接抛出异常
2、CallerRunsPolicy:调用者所在线程来运行任务
3、DiscardOrderestPolicy:丢队列最近一个任务,并执行
4、DiscardPolicy:不处理,丢掉

四种线程池

固定线程池 newFixedThreadPool
缓存线程池 newCachedThreadPool
单个线程 newSingleThreadExecutor
定时线程池 newScheduledThreadPool

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

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


    //单个线程池
    public static ExecutorService newSingleThreadExecutor() {
        return new ThreadPoolExecutor( 1, 1,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>() );
    }

    //定时线程池
    public static ExecutorService newScheduledThreadPoolExecutor(int corePoolSize) {
        return new ThreadPoolExecutor( corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
                new ScheduledThreadPoolExecutor.DelayedWorkQueue() );
    }

任务性质分类

获得cpu个数

        int cpu = Runtime.getRuntime().availableProcessors();

CPU密集型:Ncpu+1
IO密集型:2* Ncpu
混合型:线程池分解

示例代码pool

https://github.com/yinlingchaoliu/juc.git

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。