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


测试代码如下:

package cn.jdy.tools;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 如何合理地估算线程池大小
 * 如果是CPU密集型应用,则线程池大小设置为N+1
        如果是IO密集型应用,则线程池大小设置为2N+1
 * http://ifeve.com/how-to-calculate-threadpool-size/
 */
public class TestThreadPool {
	private static final int NTHREADS = 9;  
    private static final ExecutorService exec = Executors.newFixedThreadPool(NTHREADS);
//    private static final ExecutorService exec = Executors.newCachedThreadPool();
    // 使用 CachedThreadPool 比较耗内存,并发 200+的时候 会造成内存溢出
    static long tempcount = System.currentTimeMillis()/1000;// 用于计算每秒时间差
    static int prenum = 200;// 用于计算任务数量差
    static int nums = 200;// 总任务数
    static int uses = 0;// 耗时 计数
    
    static long allstart = System.currentTimeMillis();// 程序启动时间 用于计算总耗时
    static long logstime = 0;// 日志总耗时
    
    public static void main(String[] args)  {
    	//QPS(TPS):每秒钟request/事务 数量 ,QPS(TPS)= 并发数/平均响应时间
        //并发数: 系统同时处理的request/事务数
        //响应时间:  一般取平均响应时间
    	
    	for (int i = 0; i < nums; i++) {
    		Runnable task = new  Runnable() {  
                @Override
                public void run() {  
            		try {
            			long start = System.currentTimeMillis();
            			task();
            			long use = System.currentTimeMillis()-start;
//            			System.out.println("单个耗时"+use);
            			getCurrentThreads(use);
        			} catch (Exception e) {
        				e.printStackTrace();
        			}
                }
                
                /**
                 * 任务目标
                 */
                public void task(){
                	try {
//                		String url = "http://10.0.132.45:8080/filesystemweb/group1/M00/06/EF/CgCAjlhsRRqACEjcAAGcE3wG_pw989.pdf";
//						byte[] b = PdfCovertImgUtils.getInstance().getProtocolImg(new URL(url));
					} catch (Exception e) {
						e.printStackTrace();
					}
                }
            };  
            exec.execute(task);  
		}
    }

    /**
     * 每个任务分析
     * @param use 单个任务耗时
     */
    public static void getCurrentThreads(long use){
//    	Map<Thread, StackTraceElement[]> maps = Thread.getAllStackTraces();
//    	System.out.println("Threads:"+maps.size()+"-currentThread:"+Thread.currentThread().getName()+"-"+Thread.currentThread().getId());
    	
    	long start = System.currentTimeMillis();
    	
    	prenum = prenum-1;// 任务数量 进度扣减
    	uses += use;
    	
    	long now = System.currentTimeMillis()/1000; 
		if(now > tempcount){// 每秒输出一次
			long freeMemory=Runtime.getRuntime().freeMemory() / 1024 / 1024;//已使用内存
			long totalMemory=Runtime.getRuntime().totalMemory() / 1024 / 1024;//总共可使用内存
			int cpu = Runtime.getRuntime().availableProcessors();//可用cpu逻辑处理器
			
			System.out.printf("第%s秒: ", now-allstart/1000);
			int ts = (nums-prenum);//每秒事务数
			System.out.printf("每秒处理数:%s ", ts);
			System.out.printf("平均耗时:%s ", ts==0?0:uses/ts);
			System.out.printf("进度:%s ", nums);
			System.out.printf("剩余:%s毫秒 ", nums*ts);
			System.out.printf("可用内存:%sm ", freeMemory);
			System.out.printf("可用总内存:%sm \n", totalMemory);
			tempcount = now;
			nums = prenum;
			uses =0;
		}
		
		logstime += System.currentTimeMillis()-start;// 日志耗时累计
		
		// 当任务执行完了以后 计算总耗时
		if(prenum==0){
			long alluse = System.currentTimeMillis()-allstart;
			System.out.printf("总耗时%s毫秒,其中日志耗时%s毫秒\n",alluse,logstime);
			System.exit(0);
		}
		
    }
    
}



  • 7
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`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()` 来关闭线程池。 希望这可以帮助到你!如果你有更多问题,请随提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值