zoukankan      html  css  js  c++  java
  • 线程池(2)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
  • 相关阅读:
    word break II
    leetcode新题
    tensorflow数据读取过程
    python文本编辑: re.sub-------读取文本,去除指定字符并保存
    Anaconda安装及虚拟环境搭建教程(linux)
    语音合成
    关于Python错误提示: 'str' object is not callable
    语音识别学习阶段性总结(一)
    kaldi学习
    kaldi学习
  • 原文地址:https://www.cnblogs.com/yaoyuan2/p/9606476.html
Copyright © 2011-2022 走看看