I am trying to calculate faster my program. But using thread makes it more slowly. Here is the code that simplified:
In this array, trying to sum every digits. For example: unit digits = 3 + 6
List<String> myArr = new ArrayList<String>();
myArr.add("123");
myArr.add("456");
When calculate like this:
/* NORMAL USE */
long startTime1 = System.nanoTime();
int units=0; int tens=0; int hundreds=0;
for(int i=0; i < myArr.size(); i++) {
units += Character.getNumericValue(myArr.get(i).charAt(2));
tens += Character.getNumericValue(myArr.get(i).charAt(1));
hundreds += Character.getNumericValue(myArr.get(i).charAt(0));
}
long endTime1 = System.nanoTime();
double estimatedTime1 = (endTime1 - startTime1)/1000000.0;
System.out.println(estimatedTime1 + " milliseconds");
Output:
0.0285 milliseconds
When calculate using Thread:
/* USING THREAD */
ExecutorService pool = Executors.newFixedThreadPool(3);
long startTime2 = System.nanoTime();
pool.execute(new UnitsDigit(myArr));
pool.execute(new TensDigit(myArr));
pool.execute(new HundredsDigit(myArr));
pool.shutdown();
long endTime2 = System.nanoTime();
double estimatedTime2 = (endTime2 - startTime2)/1000000.0;
System.out.println(estimatedTime2 + " milliseconds");
Output:
2.5015 milliseconds
Which part i am doing wrong? Thread should be faster.
A typical newbie misconception: using multiple threads doesn't necessarily lead to faster execution!
Threads are in the end managed by the underlying operating system. Creating such threads comes therefore with a certain amount of overhead! Therefore using multiple threads makes sense only when the corresponding "tasks" have a certain duration. Beyond that, you also need a CPU able to run all the threads in parallel, otherwise you again lose against doing that computational work using a single thread.
In other words: throwing multiple threads on a simple computation that only needs "relatively few" milli or nanoseconds to complete achieves slower execution times!
Finally: the real benefit of multiple threads comes into existence when your threads spend a significant time waiting for something to happen (like doing file io).
So: when you intend to do meaningful experiments with one thread versus many, you have to incorporate such details when defining your setup.