线程与线程池,实例比较。

王朝学院·作者佚名  2016-05-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

线程与线程池,实例比较。线程池:

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 1722 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 335562 200000

总结:差异在于线程池是复用线程的,而不使用线程池是每次都要去创建线程。线程中执行工作很简单,创建线程的开销占整个时间的比例较大。

复制去Google翻译翻译结果

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航