星空网 > 软件开发 > Java

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

线程池:

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翻译翻译结果
 




原标题:线程与线程池,实例比较。

关键词:线程

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

Dealdoktor_德国折扣网:https://www.ikjzd.com/w/1603
Sparblog_德国销售折扣网:https://www.ikjzd.com/w/1604
Dealbunny:https://www.ikjzd.com/w/1605
2Checkout_支付商_数字商务:https://www.ikjzd.com/w/1606
柠檬树:https://www.ikjzd.com/w/1607
Mytopdeals:https://www.ikjzd.com/w/1608
合肥有什么约会的地方好玩的地方 合肥哪里适合情侣好玩的地方:https://www.vstour.cn/a/411237.html
曾家山滑雪场-曾家山滑雪场号码:https://www.vstour.cn/a/411238.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流