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

在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次数较大的情形,因为每循环一次,就开辟一个线程,开销较大。注意这种不叫高并发,只是相当于原来由一个工人干的活现在由多个工人协作完成一样。

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值