日期:2014-05-20  浏览次数:20669 次

和大牛们确认一个关于线程池的,疑惑了很久的问题
java5中有线程池的概念,以前我理解,创建一个线程池比如
ExecutorService exec = Executors.newFixedThreadPool(10);那么线程池里自然初始就会出现10个线程

现在我感觉好像不是这么回事,它是根据来的任务比如来了5个任务,那么就创建5个线程,也就是说以前线程池里是没有线程的,是根据来的任务才创建了线程,而且每个线程完成任务后,还会回收到线程池里去接着复用而不是被销毁死掉.

不知道我理解的对不对,请大牛们指点指点

------解决方案--------------------

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



public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }


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