Java多线程11:线程池

一、使用线程池和不使用线程池的差别

  看一下使用线程池和不使用线程池时间上的差别。以下代码使用线程池

public class test {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        LinkedList<Integer> linkedList = new LinkedList<>();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100, 100, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(20000));
        Random random = new Random();
        for (int i = 0; i < 20000; i++)
        {
            threadPoolExecutor.execute(new Runnable()
            {
                public void run()
                {
                    linkedList.add(random.nextInt());
                }
            });
        }
        threadPoolExecutor.shutdown();
        try
        {
            threadPoolExecutor.awaitTermination(1, TimeUnit.DAYS);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        System.out.println(System.currentTimeMillis() - startTime);
        System.out.println(linkedList.size());

    }
}

  执行结果:

94
20000

  接着是不使用线程池的

public class test {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        List<Integer> linkedList = new LinkedList<Integer>();
        Random random = new Random();
        for (int i = 0; i < 20000; i++)
        {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    {
                        linkedList.add(random.nextInt());
                    }
                }
            });
            thread.start();
        }
        System.out.println(System.currentTimeMillis() - startTime);
        System.out.println(linkedList.size());

    }
}

  执行结果:

2480
19235

  可以看到,使用线程池花费的时间是94ms,不使用线程池花费的时间是2480ms,差别显而易见。

猜你喜欢

转载自www.cnblogs.com/zfyang2429/p/11096340.html