一种利用线程池进行for循环处理的思想

来源:互联网 发布:阿里云ceo 编辑:程序博客网 时间:2024/05/22 16:52

在for里面,如果执行一次for里面的内容所需时间“较长”(相对而言),不妨改用线程池的方式。

如下测试:

public class ExecutorTest2 {private static final int loopNum = 1*10;          public static void main(String args[]) throws InterruptedException {      ExecutorTest2 TestThreadPool = new ExecutorTest2();          long bt = System.currentTimeMillis();          TestThreadPool.m1();          long et2 = System.currentTimeMillis();          System.out.println("[1]耗时:"+(et2 - bt)+ "ms");          Thread thread = new Thread();          long at = System.currentTimeMillis();          TestThreadPool.m2();        long et3 = System.currentTimeMillis();        System.out.println("[2]耗时:"+(et3 - at)+ "ms");              }        public void m1() {        ExecutorService pool = Executors.newCachedThreadPool();          for (int index = 0; index < loopNum; index++) {              Runnable run = new Runnable() {                  public void run() {                      try {                          new Thread().sleep(1000);  //模拟耗时操作                    System.out.println("[1]" + Thread.currentThread().getName());                    } catch (Exception e) {                      }                  }              };             pool.execute(run);          }          System.out.println("[1] done!");        pool.shutdown();      }        public void m2() {     AtomicInteger connectionIds = new AtomicInteger(0);        for (int index = 0; index < loopNum; index++) {              try {                  new Thread().sleep(1000);  //模拟耗时操作                System.out.println("[2]" + Thread.currentThread().getName());                            } catch (Exception e) {                  e.printStackTrace();              }         }          System.out.println("[2] done!");    }  }

 打印结果:

[1] done!

[1]耗时:6ms

[1]pool-1-thread-9

[1]pool-1-thread-7

[1]pool-1-thread-2

[1]pool-1-thread-1

[1]pool-1-thread-3

[1]pool-1-thread-4

[1]pool-1-thread-6

[1]pool-1-thread-5

[1]pool-1-thread-10

[1]pool-1-thread-8

[2]main

[2]main

[2]main

[2]main

[2]main

[2]main

[2]main

[2]main

[2]main

[2]main

[2] done!

[2]耗时:10005ms

 

由打印结果可知:m1方法是用到了多线程的,多线程此时被线程池管理;而m2方法始终是main主线程执行的。

采用先把要执行的“耗时”内容放到一个线程的执行主体(run方法)里面,再用线程池执行该线程,可大大减少for循环的耗时。但这种情况不适合for次数较大的情形,因为每循环一次,就开辟一个线程,开销较大。注意这种不叫高并发,只是相当于原来由一个工人干的活现在由多个工人协作完成一样。

1 0