• Java:ThreadPool


    ThreadPool(线程池)

    在Java中通过Executor可以创建线程池,创建线程池的方式有以下三种:

    1.ExecutorService exec = Executors.newCachedThreadPool();

       CacheThreadPool在程序执行的过程中通常会创建与所需数量相同的线程,然后它回收旧线程的时候停止创建新线程。

       因此它是合理的Executor的首选。

    2.ExecutorService exec = Executors.newFixedThreadPool();

       FixedThreadPool可以一次性预先执行代价高昂的线程分配,因而也就可以限制线程的数量了。

       一般只有在CacheThreadPool会引发问题时,才考虑使用FixedThreadPool。

    3.ExecutorService exec = Executors.newSingleThreadExecutor();

       SingleThreadExecucor就像是线程数量为1的FixedThreadPool。

       如果向SingleThreadExecutor提交了多个任务,那么这些任务将排队,每个任务都会在下一个任务开始之前结束,所有的任务都将使用同一个线程。

       因此,SingleThreadExecutor会序列化所有提交给它的任务,并会维护它自己(隐藏)的悬挂任务队列。

     1 public class ExecutorDemo {
     2     
     3     public static void main(String[] args) {
     4         ExecutorService exec = Executors.newSingleThreadExecutor();
     5         for (int i = 0; i < 5; i++) {
     6             exec.execute(new Runnable() {
     7 
     8                 @Override
     9                 public void run() {
    10                     System.out.println("Thread Id: " + Thread.currentThread().getId());
    11                     for (int i = 0; i < 10; i++) {
    12                         if (i > 0) {
    13                             System.out.print("," + i);
    14                         } else {
    15                             System.out.print("" + i);
    16                         }
    17                     }
    18                     System.out.println();
    19                 }
    20                 
    21             });
    22         }
    23     }
    24 }
    25 
    26 /**
    27  * 程序运行结果:
    28  * Thread Id: 9
    29  * 0,1,2,3,4,5,6,7,8,9
    30  * Thread Id: 9
    31  * 0,1,2,3,4,5,6,7,8,9
    32  * Thread Id: 9
    33  * 0,1,2,3,4,5,6,7,8,9
    34  * Thread Id: 9
    35  * 0,1,2,3,4,5,6,7,8,9
    36  * Thread Id: 9
    37  * 0,1,2,3,4,5,6,7,8,9
    38  */
    ExecutorDemo.java

  • 相关阅读:
    用js实现双色球
    nodejs_理解Buffer
    nodejs_buffer.copy
    nodejs_buffer.concat
    nodejs_buffer.alloc
    Ant Design Pro v4 最新版安装(跳过所有坑)
    python eventlet详解
    python 超时重试方法
    pycharm配置react
    Python性能优化的20条建议
  • 原文地址:https://www.cnblogs.com/slowalker/p/3377862.html
Copyright © 2020-2023  润新知