线程池学习

来源:互联网 发布:中国联合工程公司知乎 编辑:程序博客网 时间:2024/06/10 12:52

线程池、数据库连接池这些名词我们听过很多了。数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏。这项技术能明显提高对数据库操作的性能。线程池能减少系统创建、销毁线程的开销,对线程进行有效的管理和复用。

有关线程池ThreadPoolExecutor 源码的解读可以阅读文章:http://blog.csdn.net/clevergump/article/details/50688008

在学习阿里代码规范的过程中看到这一个强制的要求,

而Executors创建FixedThreadPool、SingleThreadPool、CachedThreadPool和ScheduleThreadPool的源码如下:

    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {        return new ThreadPoolExecutor(nThreads, nThreads,                                      0L, TimeUnit.MILLISECONDS,                                      new LinkedBlockingQueue<Runnable>(),                                      threadFactory);    }    public static ExecutorService newSingleThreadExecutor() {        return new FinalizableDelegatedExecutorService            (new ThreadPoolExecutor(1, 1,                                    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 ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {        return new ScheduledThreadPoolExecutor(corePoolSize);    }    public ScheduledThreadPoolExecutor(int corePoolSize) {        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,              new DelayedWorkQueue());    }

从源码中可以看出,

FixedThreadPool和SingleThreadPool允许创建线程数为threads和1,请求LinkedBlockingQueue队列长度为Integer.MAX_VALUE;

CachedThreadPool和ScheduleThreadPool允许创建线程数为Integer.MAX_VALUE,CachedThreadPool采用SynchronousQueue队列,

ScheduleThreadPool采用DelayedWorkQueue。

在eclipse的阿里代码规范插件中使用Executors创建线程池会提示warning,使用ThreadPoolExecutor创建线程池也会提示指明队列的创建和大小

原创粉丝点击