Java Threadpool

来自WHY42

JDK提供了ExecutorService以提供线程池的应用,今天测试了一下线程池的使用,受益匪浅。

线程计数

使用CountDownLatch锁来对线程执行结果进行倒数,当所有线程执行完之后,计算出耗时。

static final int testCount = 1000000;
static final int sleep = 10;
public static void main(String[] args){
    System.out.println("Hello!");

    HelloPool hold = new HelloPool();

    Date t1 = new Date();
    hold.normalThread();
    Date t2 = new Date();
    System.out.println("\nNormal cost:" + (t2.getTime() - t1.getTime()));

    t1 = new Date();
    hold.useThreadPool();
    t2 = new Date();
    System.out.println("\nNormal cost:" + (t2.getTime() - t1.getTime()));        
}

不使用线程池

void normalThread(){
    final CountDownLatch lock = new CountDownLatch(testCount);
    for(int i = 0; i < testCount; i++){
        final int item = i;
        Thread t = new Thread(new Runnable(){

            @Override
            public void run() {
                handle(item);
                lock.countDown();
            }

        });
        t.start();
    }
    try {
        lock.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

使用线程池

void useThreadPool(){
    final CountDownLatch lock = new CountDownLatch(testCount);
    final ExecutorService pool = Executors.newCachedThreadPool();
    for(int i = 0; i < testCount; i++){
        final int item = i;
        pool.execute(new Runnable(){
            @Override
            public void run() {
                handle(item);
                lock.countDown();
            }

        });
    }
    try {
        lock.await();
        pool.shutdown();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

测试结果

当线程数少的时候,差别并不是很明显。当如上图的线程数达到一定数量时,差别就出来了:

Hello!
0 100000 200000 300000 400000 500000 600000 700000 800000 900000 
Normal cost:61156
0 100000 200000 300000 400000 500000 600000 700000 800000 900000 
Normal cost:3571

而且前者在执行时,CPU资源一直耗尽(100% of Intel@I7 4700m 4Core),显然后者更优秀了。