I am traying to get a small idea about Threads. I want to : for instance
-ExecutorService: check for how many threads it will find the max of the array faster
when using 2/4/6/8
then to sout :
best time
average time
worst time
What I did is :
Main class:
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadEx {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2); // example using 2 threads
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // I have to make max
Runnable run = () -> {
list.parallelStream()
.map(sum -> list.stream() // I don't know how to make it here do only
print once the sum not to print the sum every time for each element = 10 times = 10 elements
.mapToInt(Integer::intValue)
.max())
.forEach(System.out::println);
};
long start = System.currentTimeMillis(); //Start time
executorService.execute(run); // running the task
long end = System.currentTimeMillis(); //End time
System.out.println(end - start); // time spent total
executorService.shutdown();
}
}
So short story I want to make sum of elements using 2 threads(as in my example)and then sout the time spent for executing the task
Further I want to make same method but using Executors.newFixedThreadPool(4)(6)(8) threads and so on
I assume the fact that I use a Runnable to be able to make a sum is not a good idea.
since if I call
Integer run = list.stream()
.mapToInt(Integer::intValue)
.sum();
It cannot be because it must return an int
Can someone give me and hint please? Any advice/hints/minuses are welcome Thanks