ljoedicke
ljoedicke

Reputation: 37

Java process one array with multiple threads

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();
        }

    }

Upvotes: 2

Views: 2078

Answers (1)

Sercan
Sercan

Reputation: 2169

For your purpose in above given example, you do not need to split your array to pass the parts to parallel threads. Using parallel streams to process elements of an array will do it for you:

public static void main(String... args) {
    int[] integerArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    Arrays.stream(integerArray)
            .parallel()
            .forEach(x -> System.out.println(Thread.currentThread().getName() + " printed value: " + x));
}

On output, you can see that ForkJoinPool-Worker-Threads will be working to print your elements.

Upvotes: 2

Related Questions