I want to execute some tasks parallel so I was searching for multithreading in Java and I found this class, ExecutorService. I tried with simple example but I am not sure whether it is running in parallel.
long startTime = System.currentTimeMillis();
List<Callable<String>> callables = new ArrayList<Callable<String>>();
ExecutorService executor = Executors.newCachedThreadPool();
callables.add(new Callable<String>() {
public String call() {
for (int i=0; i<100000; i++) {
System.out.println("i "+i);
}
return "Task 1";
}
}
);
callables.add(new Callable<String>() {
public String call() {
for (int j=0; j<100000; j++) {
System.out.println("j "+j);
}
return "Task 2";
}
}
);
callables.add(new Callable<String>() {
public String call() {
for (int k=0; k<100000; k++) {
System.out.println("k "+k);
}
return "Task 3";
}
}
);
try {
List<Future<String>> futureLst = executor.invokeAll(callables);
for (Future future : futureLst) {
try {
System.out.println(future.get());
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown();
System.out.println("Time Taken - "+ (System.currentTimeMillis() - startTime));
The above code works fine as expected and prints the count and returns the string. The time taken for the above program to execute is "3229" milliseconds.
I rewrote the above program as below,
long startTime = System.currentTimeMillis();
for (int i=0; i<100000; i++) {
System.out.println("i "+i);
}
for (int j=0; j<100000; j++) {
System.out.println("j "+j);
}
for (int k=0; k<100000; k++) {
System.out.println("k "+k);
}
System.out.println("Time Taken - "+ (System.currentTimeMillis() - startTime));
The time taken for this program is "3104" milliseconds which is lesser than the one coded with executing parallel.
So am I doing anything wrong in first program ? Is my first program running tasks in parallel, since I see without thread is taking less time?