首页 > 编程语言 > 详细

5.关于线程池的一些要点总结

时间:2021-04-09 09:41:28      阅读:14      评论:0      收藏:0      [点我收藏+]

1.核心线程是否会被回收?

不会被回收,除非手动设置allowCoreThreadTimeOut参数

2.keepAliveTime的含义

这个参数的含义是指当线程池中线程数量大于corePollSize时,此时存在非核心线程,keepAliveTime指非核心线程空闲时间达到的阈值会被回收。

3.常见的三个线程池

    ExecutorService service = Executors.newFixedThreadPool(20);
    ExecutorService service2 = Executors.newCachedThreadPool();
    ExecutorService service3 = Executors.newSingleThreadExecutor();

  1)固定大小线程池

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

  2)单个线程的线程池

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

  它两唯一的区别是传入参数作为核心线程大小和固定为1

       3)缓冲线程池

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

  它用到了同步队列,没有内存开销问题

4.工作中的线程池

队列一般设置成ArrayBlockQueue,大小设置成500,核心的线程数根据机器的核数*2+1来设置,这样是为了更好利用资源,又不让系统OOM

 

 

源码解读:

https://www.cnblogs.com/semi-sub/p/13908099.html

5.关于线程池的一些要点总结

原文:https://www.cnblogs.com/johnzhao/p/14635456.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!