线程池:
int count = 200000; long startTime = System.currentTimeMillis(); final List<Integer> l = new LinkedList<Integer>(); ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(count)); final Random random = new Random(); for (int i = 0; i < count; i++) { tp.execute(new Runnable() { @Override public void run() { l.add(random.nextInt()); } }); } tp.shutdown(); try { tp.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(System.currentTimeMillis() - startTime); System.out.println(l.size());
输出结果:
1 172 2 200000
线程:
int count = 200000; long startTime = System.currentTimeMillis(); final List<Integer> l = new LinkedList<Integer>(); final Random random = new Random(); for (int i = 0; i < count; i++) { Thread thread = new Thread(){ @Override public void run(){ l.add(random.nextInt()); } }; thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(System.currentTimeMillis() - startTime); System.out.println(l.size());
输出结果:
1 33556 2 200000
总结:差异在于线程池是复用线程的,而不使用线程池是每次都要去创建线程。线程中执行工作很简单,创建线程的开销占整个时间的比例较大。
复制去Google翻译翻译结果
时间: 2024-10-27 08:53:07