线程池多线程比较实例

本实例是一个比较多线程的一个小例子,

testThreadPool1与testThreadPool2 比较了shutdown与shutdownNow的区别;

testThreadPool3与testThreadPool4比较了匿名内部类直接new Callable,与先new Callable出来,放入到List中再执行的效率差别;

testThreadPool4与testThreadPool5比较线程池中固定线程个数对效率的影响;

testThreadPool5与testQueue();比较了采用多线与不采用多线程之间的效率比较。

测试例子如下:

package com.tgb.lk.demo.thread.threadPool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by likun on 2014/9/26.
 */
public class ThreadPool {
    private static int total = 10000;

    public static void main(String[] args) {
        try {
            testThreadPool1();//shutdown
            Thread.currentThread().sleep(3000);

            testThreadPool2();//shutdownNow,比较与1中shutdown的区别
            Thread.currentThread().sleep(total / 5);

            testThreadPool3();//匿名内部类,直接new Callable
            Thread.currentThread().sleep(1000);

            testThreadPool4();//先new Callable出来,放入到List中再执行,与3比较效率
            Thread.currentThread().sleep(1000);

            testThreadPool5();//4与5比较线程池中固定线程个数对效率的影响
            Thread.currentThread().sleep(1000);

            testQueue();//不采用多线程,在主线程中循环执行
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public static void execute(String s) {
        System.out.print(s);
        //System.out.print("");
        try {
            Thread.currentThread().sleep(2);
        } catch (InterruptedException e) {
            System.err.println("error:" + Thread.currentThread().getName() + " " + e.getMessage());
        }
    }

    public static void testThreadPool1() {
        System.out.println("\n &&&&&&&&&&testThreadPool1 start running----------->");
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        final long start = System.currentTimeMillis();
        for (int i = 0; i <= total; i++) {
            final int j = i;
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    execute("1");
                }
            });
        }
        long end = System.currentTimeMillis();
        System.out.println("\n &&&&&&&&&&testThreadPool1 spend time=" + (end - start) + "ms");//注意这里打印的仅是主线程中循环所花费的时间,并不代表执行完所有内容所花费的时间
        System.out.println("warn:this time is not the total spend time,this only is the 'for()' spend time");
        //threadPool.shutdownNow();
        threadPool.shutdown();
        //shutdown()只是将空闲的线程interrupt()了,因此在shutdown()之前提交的任务可以继续执行直到结束。
        //shutdownNow()是interrupt所有线程,已执行完的不管,正在线程池中执行的任务interrupt了,未调入到线程池中的任务直接终止。
        //shutdownNow()比较暴力,可能导致正在运行中的任务抛出异常
    }

    public static void testThreadPool2() {
        System.out.println("\n @@@@@@@@@@testThreadPool2 start running----------->");
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        final long start = System.currentTimeMillis();
        for (int i = 0; i <= total; i++) {
            final int j = i;
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    execute("2");
                }
            });
        }
        long end = System.currentTimeMillis();
        System.out.println("\n @@@@@@@@@@testThreadPool2 spend time=" + (end - start) + "ms");//注意这里打印的仅是主线程中循环所花费的时间,并不代表执行完所有内容所花费的时间
        System.out.println("warn:this time is not the total spend time,this only is the 'for()' spend time");
        threadPool.shutdownNow();
        //threadPool.shutdown();
        //shutdown()只是将空闲的线程interrupt()了,因此在shutdown()之前提交的任务可以继续执行直到结束。
        //shutdownNow()是interrupt所有线程,已执行完的不管,正在线程池中执行的任务interrupt了,未调入到线程池中的任务直接终止。
        //shutdownNow()比较暴力,可能导致正在运行中的任务抛出异常
    }

    public static void testThreadPool3() {
        System.out.println("\n #########testThreadPool3 start running----------->");
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        final long start = System.currentTimeMillis();
        Future<Integer> future = null;
        for (int i = 0; i <= total; i++) {
            final int j = i;
            future = threadPool.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    execute("3");
                    return j;
                }
            });
        }
        try {
            if (future != null && future.get() == total) {
                long end = System.currentTimeMillis();
                System.out.println("\n #########testThreadPool3 time spent = " + (end - start) + " ms");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

    public static void testThreadPool4() {
        System.out.println(" $$$$$$$$$testThreadPool4 start running----------->");
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        try {
            List<Callable<Integer>> callableList = new ArrayList<Callable<Integer>>(total + 1);
            for (int i = 0; i <= total; i++) {
                final int j = i;
                callableList.add(new Callable<Integer>() {
                    @Override
                    public Integer call() throws Exception {
                        execute("4");
                        return j;
                    }
                });
            }
            Future<Integer> future = null;
            final long start = System.currentTimeMillis();
            for (int i = 0; i <= total; i++) {
                future = threadPool.submit(callableList.get(i));
            }
            if (future != null && future.get() == total) {
                long end = System.currentTimeMillis();
                System.out.println("\n $$$$$$$$$testThreadPool4 time spent = " + (end - start) + " ms");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

    public static void testThreadPool5() {
        System.out.println(" %%%%%%%%%%testThreadPool5 start running----------->");
        ExecutorService threadPool = Executors.newFixedThreadPool(20);
        try {
            List<Callable<Integer>> callableList = new ArrayList<Callable<Integer>>(total + 1);
            for (int i = 0; i <= total; i++) {
                final int j = i;
                callableList.add(new Callable<Integer>() {
                    @Override
                    public Integer call() throws Exception {
                        execute("5");
                        return j;
                    }
                });
            }
            Future<Integer> future = null;
            final long start = System.currentTimeMillis();
            for (int i = 0; i <= total; i++) {
                future = threadPool.submit(callableList.get(i));
            }
            if (future != null && future.get() == total) {
                long end = System.currentTimeMillis();
                System.out.println("\n %%%%%%%%%%testThreadPool5 time spent = " + (end - start) + " ms");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

    public static void testQueue() {
        System.out.println(" ^^^^^^^^^^^testQueue start running----------->");
        final long start = System.currentTimeMillis();
        for (int i = 0; i <= total; i++) {
            execute("0");
        }
        long end = System.currentTimeMillis();
        System.out.println("\n ^^^^^^^^^^^testQueue time spent = " + (end - start) + " ms");
    }
}

测试结果如下:




评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值