I'm trying to understand the advantage of using thread pools, i wrote this code to see the time improvement of fixed thread pool.
First, i set the number of threads in the pool to 1 and it took approximately 920 ms, then i changed the number of threads in the pool to 2(and 3,4,5,6,7...) and it took 1200 ms, shouldn't it be faster when the threads are running concurrently?
When i changed it to cached thread pool it also took 1200 ms
package threadpool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Example3 { public static void main(String[] args) { new Example3(); } public Example3() { try { testFixedPool(1); //testFixedPool(2); } catch (InterruptedException e) { e.printStackTrace(); } } public void testFixedPool(int numberOfThreads) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); long start = System.currentTimeMillis(); executor.execute(new TaskPrintInteger(0, 10000)); executor.execute(new TaskPrintInteger(1, 10000)); executor.execute(new TaskPrintInteger(2, 10000)); executor.execute(new TaskPrintInteger(3, 10000)); executor.execute(new TaskPrintInteger(4, 10000)); executor.execute(new TaskPrintInteger(5, 10000)); executor.execute(new TaskPrintInteger(6, 10000)); executor.execute(new TaskPrintInteger(7, 10000)); executor.execute(new TaskPrintInteger(8, 10000)); executor.execute(new TaskPrintInteger(9, 10000)); executor.shutdown(); while(!executor.isTerminated()){ } System.out.println(); System.out.println((System.currentTimeMillis()) - start); } private class TaskPrintInteger implements Runnable { private int number, times; public TaskPrintInteger(int number, int times) { this.number = number; this.times = times; } @Override public void run() { for (int i = 0; i < times; i++) { System.out.println(number); } } } }
System.out, since that synchronizes (so only one thread is printing at a time, negating any advantages of threading).System.out.println()call. That and the fact that parallel processing isn't going to boost any I/O bound process.