線程池:
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翻譯翻譯結果