Executors.newFixedThreadPool(NTHREADS)线程池数量设置多少合适?


并发编程中线程池 是跑不了的, 用过线程池的朋友 都会遇到这样的一个问题:

如何合理地估算线程池大小?

怎么样设置 数量,执行效率最高?

怎么样设置 内存消耗最低?

是不是设置 线程池数量越大越好?

多线程 是不是不一定比单线程快?( 某些场景单线程确实比多线程快)


CPU资源是有限的,多线程 并发 都是在 抢占CPU资源,线程越多 抢占越激烈,单个线程获取资源的成本变高,执行完成时间会增加;


第一次 使用newFixedThreadPool 我设置了 线程数为80;

在运行中发现,往池子中 添加大量任务,第一个任务开始执行的时间点 特别晚,

而且 内存飙的特别高,究其原因是 他要把80个线程创建了,然后开始执行任务。

每个线程占用至少好几M甚至10几M的内存。

线程多了以后 内存就持续上涨;


朋友建议 使用Executors.newCachedThreadPool();

测试发现 当线程数 添加到 200+的时候 会造成内存溢出;

所以 直接 pass掉这个方式;


以下 是我 测试 Executors.newFixedThreadPool(NTHREADS) 方式 设置不同 线程数 的执行结果:

统一设置任务数 100;相当于并发100 已经满足大多数场景了;

newFixedThreadPool =1 总耗时46251毫秒,其中日志耗时17毫秒

newFixedThreadPool =2 总耗时25870毫秒,其中日志耗时11毫秒

newFixedThreadPool =4 总耗时18424毫秒,其中日志耗时21毫秒

newFixedThreadPool =5 总耗时18447毫秒,其中日志耗时5毫秒

newFixedThreadPool =8 总耗时16807毫秒,其中日志耗时9毫秒

newFixedThreadPool =9 总耗时17946毫秒,其中日志耗时8毫秒

newFixedThreadPool =16 总耗时17201毫秒,其中日志耗时9毫秒

newFixedThreadPool =32 总耗时17661毫秒,其中日志耗时808毫秒

newFixedThreadPool =48 总耗时18277毫秒,其中日志耗时25毫秒

newFixedThreadPool =64 总耗时18000毫秒,其中日志耗时2812毫秒

newCachedThreadPool  总耗时20374毫秒,其中日志耗时3毫秒


得出这个结果之后,去百度了一下 发现了这篇文章:

http://ifeve.com/how-to-calculate-threadpool-size/

结论是:

如果是CPU密集型应用,则线程池大小设置为N+1

如果是IO密集型应用,则线程池大小设置为2N+1


测试代码如下:

[java]  view plain  copy
  1. package cn.jdy.tools;  
  2.   
  3. import java.util.concurrent.ExecutorService;  
  4. import java.util.concurrent.Executors;  
  5.   
  6. /** 
  7.  * 如何合理地估算线程池大小 
  8.  * 如果是CPU密集型应用,则线程池大小设置为N+1 
  9.         如果是IO密集型应用,则线程池大小设置为2N+1 
  10.  * http://ifeve.com/how-to-calculate-threadpool-size/ 
  11.  */  
  12. public class TestThreadPool {  
  13.     private static final int NTHREADS = 9;    
  14.     private static final ExecutorService exec = Executors.newFixedThreadPool(NTHREADS);  
  15. //    private static final ExecutorService exec = Executors.newCachedThreadPool();  
  16.     // 使用 CachedThreadPool 比较耗内存,并发 200+的时候 会造成内存溢出  
  17.     static long tempcount = System.currentTimeMillis()/1000;// 用于计算每秒时间差  
  18.     static int prenum = 200;// 用于计算任务数量差  
  19.     static int nums = 200;// 总任务数  
  20.     static int uses = 0;// 耗时 计数  
  21.       
  22.     static long allstart = System.currentTimeMillis();// 程序启动时间 用于计算总耗时  
  23.     static long logstime = 0;// 日志总耗时  
  24.       
  25.     public static void main(String[] args)  {  
  26.         //QPS(TPS):每秒钟request/事务 数量 ,QPS(TPS)= 并发数/平均响应时间  
  27.         //并发数: 系统同时处理的request/事务数  
  28.         //响应时间:  一般取平均响应时间  
  29.           
  30.         for (int i = 0; i < nums; i++) {  
  31.             Runnable task = new  Runnable() {    
  32.                 @Override  
  33.                 public void run() {    
  34.                     try {  
  35.                         long start = System.currentTimeMillis();  
  36.                         task();  
  37.                         long use = System.currentTimeMillis()-start;  
  38. //                      System.out.println("单个耗时"+use);  
  39.                         getCurrentThreads(use);  
  40.                     } catch (Exception e) {  
  41.                         e.printStackTrace();  
  42.                     }  
  43.                 }  
  44.                   
  45.                 /** 
  46.                  * 任务目标 
  47.                  */  
  48.                 public void task(){  
  49.                     try {  
  50. //                      String url = "http://10.0.132.45:8080/filesystemweb/group1/M00/06/EF/CgCAjlhsRRqACEjcAAGcE3wG_pw989.pdf";  
  51. //                      byte[] b = PdfCovertImgUtils.getInstance().getProtocolImg(new URL(url));  
  52.                     } catch (Exception e) {  
  53.                         e.printStackTrace();  
  54.                     }  
  55.                 }  
  56.             };    
  57.             exec.execute(task);    
  58.         }  
  59.     }  
  60.   
  61.     /** 
  62.      * 每个任务分析 
  63.      * @param use 单个任务耗时 
  64.      */  
  65.     public static void getCurrentThreads(long use){  
  66. //      Map<Thread, StackTraceElement[]> maps = Thread.getAllStackTraces();  
  67. //      System.out.println("Threads:"+maps.size()+"-currentThread:"+Thread.currentThread().getName()+"-"+Thread.currentThread().getId());  
  68.           
  69.         long start = System.currentTimeMillis();  
  70.           
  71.         prenum = prenum-1;// 任务数量 进度扣减  
  72.         uses += use;  
  73.           
  74.         long now = System.currentTimeMillis()/1000;   
  75.         if(now > tempcount){// 每秒输出一次  
  76.             long freeMemory=Runtime.getRuntime().freeMemory() / 1024 / 1024;//已使用内存  
  77.             long totalMemory=Runtime.getRuntime().totalMemory() / 1024 / 1024;//总共可使用内存  
  78.             int cpu = Runtime.getRuntime().availableProcessors();//可用cpu逻辑处理器  
  79.               
  80.             System.out.printf("第%s秒: ", now-allstart/1000);  
  81.             int ts = (nums-prenum);//每秒事务数  
  82.             System.out.printf("每秒处理数:%s ", ts);  
  83.             System.out.printf("平均耗时:%s ", ts==0?0:uses/ts);  
  84.             System.out.printf("进度:%s ", nums);  
  85.             System.out.printf("剩余:%s毫秒 ", nums*ts);  
  86.             System.out.printf("可用内存:%sm ", freeMemory);  
  87.             System.out.printf("可用总内存:%sm \n", totalMemory);  
  88.             tempcount = now;  
  89.             nums = prenum;  
  90.             uses =0;  
  91.         }  
  92.           
  93.         logstime += System.currentTimeMillis()-start;// 日志耗时累计  
  94.           
  95.         // 当任务执行完了以后 计算总耗时  
  96.         if(prenum==0){  
  97.             long alluse = System.currentTimeMillis()-allstart;  
  98.             System.out.printf("总耗时%s毫秒,其中日志耗时%s毫秒\n",alluse,logstime);  
  99.             System.exit(0);  
  100.         }  
  101.           
  102.     }  
  103.       
  104. }  
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
`Executors.newFixedThreadPool` 是 Java 中用于创建固定大小的线程池的工厂方法。它返回一个 `ExecutorService` 对象,该对象可以用于执行多个任务。 使用 `Executors.newFixedThreadPool` 的基本语法如下: ```java ExecutorService executor = Executors.newFixedThreadPool(int nThreads); ``` 其中,`nThreads` 是要创建的线程池中的线数量。 以下是使用 `Executors.newFixedThreadPool` 的几个要点: 1. 创建线程池后,线程池中的线程数是固定的,不会随着任务的增加而增加。 2. 如果提交的任务数量超出线程池大小,那么多余的任务将被放入队列中等待执行。 3. 如果队列已满,且所有线程都正在执行任务,则新提交的任务将等待,直到有空闲线程可用。 4. 线程池中的线程可以重用,以执行多个任务。 5. `ExecutorService` 提供了一些方法来提交任务并获得执行结果,如 `submit()` 和 `invokeAll()`。 以下是一个简单的示例代码,演示了如何使用 `Executors.newFixedThreadPool`: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class FixedThreadPoolExample { public static void main(String[] args) { // 创建一个固定大小为 5 的线程池 ExecutorService executor = Executors.newFixedThreadPool(5); // 提交 10 个任务给线程池执行 for (int i = 0; i < 10; i++) { final int taskId = i; executor.submit(new Runnable() { public void run() { System.out.println("Task " + taskId + " is being executed."); } }); } // 关闭线程池 executor.shutdown(); } } ``` 在上述示例中,我们创建了一个固定大小为 5 的线程池,并提交了 10 个任务给线程池执行。每个任务打印了自己的任务ID。最后,我们调用 `executor.shutdown()` 来关闭线程池。 希望这可以帮助到你!如果你有更多问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值