The most straight forward way is to use the Parallel Stream as nicely illustrated by @Govinda Sakhare.
However, if you want to use this example as a way of learning about how to work with Threads then to parallelize your code follow the steps below:
- Create the threads;
- Assign the work to the threads, i.e., each thread will try to find a value bigger than the one passed as parameter but only for a part of the array;
- The first Thread that founds the value notifies the others about it so that every single one exits.
To create the threads we can do the following:
Thread[] threads = new Thread[total_threads];
for(int t = 0; t < threads.length; t++) {
threads[t] = new Thread(/** the parallel work **/);
threads[t].start();
}
To assign the work to the threads, we need to split the array among the threads. The easiest way is actually split the iterations instead of the array itself. The threads receive the entire array, but only work with some of its positions, for instance:
private final static int NO_FOUND = -1;
// Linear-search function to find the index of an element
public static int findIndex(int[] arr, int t, int threadId, int total_threads){
for (int i = threadId; i < arr.length; i += total_threads)
if ( arr[i] > t)
return i;
return NO_FOUND;
}
To each thread we assign an ID range from 0 to N-1, with N being the total number of threads.
To notify the threads we can use a shared Atomic Integer among threads that will be used to update the index of the value found. So the final code would look like the following:
public class program {
private final static int NO_FOUND = -1;
// Linear-search function to find the index of an element
public static int findIndex(int[] arr, int t, int threadId, int total_threads, AtomicInteger shared_index){
for (int i = threadId; i < arr.length && shared_index.get() == -1; i += total_threads)
if ( arr[i] > t)
return i;
return NO_FOUND;
}
public static void main(String[] args) throws InterruptedException {
final int N = 8;
int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 };
int total_threads = 4;
AtomicInteger shared_index = new AtomicInteger(-1);
Thread[] threads = new Thread[total_threads];
for(int t = 0; t < threads.length; t++) {
final int thread_id = t;
threads[t] = new Thread(() ->parallel_work(N, my_array, total_threads, shared_index, thread_id));
threads[t].start();
}
for (Thread thread : threads)
thread.join();
System.out.println("Index of value bigger than " + N + " : " + shared_index.get());
}
private static void parallel_work(int n, int[] my_array, int total_threads, AtomicInteger shared_index, int thread_id) {
int index_found = findIndex(my_array, n, thread_id, total_threads, shared_index);
shared_index.compareAndExchange(NO_FOUND, index_found);
}
}
OUTPUT:
Index of value bigger than 8 : 8