I want to check which code is faster and why?
Or if we want to execute more faster than single core then How can we write the code ?
Concept : In multi threading, we used available cores to execute operation in parallel way.
But when I ran following codes , I came to know single core code is faster than both multi-threaded codes. Then what is the use of multi-threading in these kind of scenario?
Output : In both programs output you will get minutes level difference.
CODE : Declaration :
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 10000000; i++) {
list.add(i);
}
Single core : Code 1 :
while (i < 5) {
list.forEach(e -> {
System.out.println(LocalTime.now() + "- " + Thread.currentThread().getName() + " Value : " + e);
});
i++;
}
Multi-thread : Code 2 :
ExecutorService service = Executors.newFixedThreadPool(2);
while (i < 5) {
list.forEach(e -> service.execute(() -> System.out
.println(LocalTime.now() + "- " + Thread.currentThread().getName() + " Value : " + e)));
i++;
}
Multi-thread :Code 3 :
ExecutorService service = Executors.newFixedThreadPool(2);
while (i < 5) {
service.execute(() -> list.forEach(e -> System.out
.println(LocalTime.now() + "- " + Thread.currentThread().getName() + " Value : " + e)));
i++;
}