for循环效率优化

本文探讨了如何通过引入多线程优化for循环的执行效率,对比了一次性执行与多线程并行执行的性能差异。实验显示,使用10个子线程可以显著减少10次循环的总时间,但同时也增加了程序开销。因此,在选择优化策略时,需要根据实际业务场景权衡利弊。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

for循环是我们编程中经常用到的,但是如果每一次循环中耗时较久,那么整个程序就会很慢,甚至超时,下面我就来改进一下这种情况。

public class TestSynchronizedFor {
   private static final int num = 10;
   public static void main(String args[]) throws InterruptedException {
      TestSynchronizedFor testSynchronizedFor = new TestSynchronizedFor();
      long at = System.currentTimeMillis();
      testSynchronizedFor.start();
      long et3 = System.currentTimeMillis();
      System.out.println("总耗时:"+(et3 - at)+ "ms");

   }


   public static void start() {
      for (int index = 0; index < num; index++) {
         try {
            new Thread().sleep(1000);  //模拟耗时操作
            System.out.println("[2]" + Thread.currentThread().getName());

         } catch (Exception e) {
            e.printStackTrace();
         }
      }
      System.out.println("[2] done!");
   }

}
执行结果:
[2]main
[2]main
[2]main
[2]main
[2]main
[2]main
[2]main
[2]main
[2]main
[2]main
[2] done!
总耗时:10076ms

我们人为的在让每一次循环中耗时1s,10次循环下来总的时间为10s多一点。这是我们这样没有任何改进的时候,接下来,我们把这段代码改动一下。

public class TestAsynchronousFor {
   private static final int num = 10;
   public static void main(String args[]) throws InterruptedException {
      TestAsynchronousFor testAsynchronousFor = new TestAsynchronousFor();
      long bt = System.currentTimeMillis();

      testAsynchronousFor.start();
      long et3 = System.currentTimeMillis();
System.out.println("伴随线程"+Thread.currentThread().getName()+"正在执行中" );
      System.out.println("总耗时:"+(et3 - bt)+ "ms");

   }

   public static void start() {
      ExecutorService pool = Executors.newCachedThreadPool();
      for (int i = 0; i < num; i++) {
         Runnable run = new Runnable() {
            public void run() {
               try {
                  new Thread().sleep(1000);
                  //模拟耗时操作
                  System.out.println( Thread.currentThread().getName()+"执行了" );
               } catch (Exception e) {
               }
            }
         };
         pool.execute(run);

      }
      pool.shutdown();
      while (true) {
         if (pool.isTerminated()) {
            System.out.println("所有的子线程都结束了!");
            break;
         }
         try {
            new Thread().sleep(1000);
         } catch (Exception e) {
         }
      }
   }
}

执行结果:
pool-1-thread-1执行了
pool-1-thread-2执行了
pool-1-thread-7执行了
pool-1-thread-6执行了
pool-1-thread-5执行了
pool-1-thread-4执行了
pool-1-thread-3执行了
pool-1-thread-9执行了
pool-1-thread-8执行了
pool-1-thread-10执行了
所有的子线程都结束了!
伴随线程main正在执行中
总耗时:2021ms

两次执行
执行差异 执行用时 运用线程数量
第一次 10076ms 1个(main线程)
第二次 2068ms 11个(10个子线程+1个主线程)

对比执行用时使用线程数量
第一次10076ms1个(main线程)
第二次2068ms11个(10个子线程+1个main线程)

通过比较我们发现第二次的用时大约为2s,时间上是大大的减少了,我们分析一下具体差异。第一次执行是main线程一个线程执行完了10次任务,第二次是10个子线程处理了10次任务,相当于原来1个工人的产量任务分给了10个人协同完成。这种方式虽然减少了for循环的用时,但是这种做法不适用于for次数较大的情况,因为每循环一次就开辟了一个线程,对于程序的开销变大。选用哪种方式还要综合考量我们的业务场景。

在这里插入图片描述
商标检索小程序
在这里插入图片描述
专利翻译小程序
在这里插入图片描述
专利检索小程序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值