线程池Executors.newFixedThreadPool

Posted yaoyuan2

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程池Executors.newFixedThreadPool相关的知识,希望对你有一定的参考价值。

例子:

ExecutorService es = Executors.newFixedThreadPool(5);
        try {
            for (int i = 0; i < 20; i++) {
                Runnable syncRunnable = new Runnable() {
                    @Override
                    public void run() {
                        log.info(Thread.currentThread().getName());
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                };
                es.execute(syncRunnable);
            }
        } finally {
            es.shutdown();
        }
运行结果:
         *  10:20:14.630 pool-1-thread-5
            10:20:14.630 pool-1-thread-1
            10:20:14.632 pool-1-thread-4
            10:20:14.630 pool-1-thread-2
            10:20:14.630 pool-1-thread-3
            10:20:16.635 pool-1-thread-4
            10:20:16.635 pool-1-thread-5
            10:20:16.635 pool-1-thread-1
            10:20:16.636 pool-1-thread-2
            10:20:16.637 pool-1-thread-3
            10:20:18.637 pool-1-thread-3
            10:20:18.638 pool-1-thread-4
            10:20:18.641 pool-1-thread-5
            10:20:18.641 pool-1-thread-1
            10:20:18.642 pool-1-thread-2
            10:20:20.638 pool-1-thread-3
            10:20:20.639 pool-1-thread-4
            10:20:20.641 pool-1-thread-5
            10:20:20.642 pool-1-thread-1
            10:20:20.642 pool-1-thread-2

调用的ThreadPoolExecutor:

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

 

corePoolSize=maximumPoolSize=5

keepAliveTime=0

allowCoreThreadTimeout=false(默认)

因此,

  • 线程池中的线程数永远是5,永久存活。
  • 对于新任务,当队列未满时,插入队列;当队列已满时,默认执行AbortPolicy,即抛出异常。
  • 支持线程reuse

 

以上是关于线程池Executors.newFixedThreadPool的主要内容,如果未能解决你的问题,请参考以下文章

自己实现一个简单的线程池

什么叫线程池?线程池如何使用?

多线程(六):线程池

多线程(六):线程池

十五、线程池(六)自动创建线程池的弊端

java 如何获得线程池中正在执行的线程数?