Compare threads with thread pools and instances ., Thread Pool instance comparison
Thread Pool:
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());
Output result:
1 1722 200000
Thread:
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());
Output result:
1 335562 200000
Conclusion: The difference is that the thread pool is used to reuse threads, instead of using the thread pool, the thread is created every time. The execution in the thread is very simple, and the overhead of the thread creation accounts for a large proportion of the whole time.
Copy the Translation results to Google