I want to implement multiple Threads in my program. These multiple Threads should be able to process one single array.
For example:
I have an integer array:
int[] integerArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Now, multiple Threads should print every item to the console, like this:
1 //Printed by Thread 1
2 //Printed by Thread 2
7 //Printed by Thread 1
8 //Printed by Thread 2
9 //Printed by Thread 3
4 //Printed by Thread 1
5 //Printed by Thread 2
6 //Printed by Thread 3
3 //Printed by Thread 3
10 //Printed by Thread 1
11 //Printed by Thread 2
12 //Printed by Thread 3
(It doesn't matter if the result is random or not.)
My solution so far was to split the array into smaller chunks. This is working, but I don't really like the solution and I don't think that this would be really thread-safe
public static void main(String[] args) {
int[] integerArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
int chunk = 3;
for (int i = 0; i < integerArray.length; i += chunk) {
int finalI = i;
new Thread(() -> {
int[] splittedArray = Arrays.copyOfRange(integerArray, finalI, Math.min(integerArray.length, finalI + chunk));
for (int value : splittedArray) {
System.out.println(value);
}
}).start();
}
}
parallelStream: stackoverflow.com/questions/40933362/…