因此,我有一个函数,可以在下面显示的大型未排序数字数组中找到大于N的数字。
import java.util.*;
public class program {
// Linear-search function to find the index of an element
public static int findIndex(int arr[], int t)
{
// if array is Null
if (arr == null) {
return -1;
}
// find length of array
int len = arr.length;
int i = 0;
// traverse in the array
while (i < len) {
// if the i-th element is t
// then return the index
if (arr[i] > t) {
return i;
}
else {
i = i + 1;
}
}
return -1;
}
// Driver Code
public static void main(String[] args)
{
int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 };
int i = findIndex(my_array, 7);
// find the index of 5
System.out.println("Index position of 5 is: "
+ my_array[i]);
}
}
但是我必须找到一种并行实现此方法的方法。我不确定如何开始或究竟要做什么,因为我在并行编程领域还很陌生。
任何帮助将不胜感激。
最直接的方法是使用@Govinda Sakhare很好地说明的并行流。
但是,如果您想使用此示例作为学习如何使用线程的方法,请按照以下步骤并行化代码:
要创建线程,我们可以执行以下操作:
Thread[] threads = new Thread[total_threads];
for(int t = 0; t < threads.length; t++) {
threads[t] = new Thread(/** the parallel work **/);
threads[t].start();
}
要将工作分配给线程,我们需要在线程之间拆分数组。最简单的方法实际上是拆分迭代而不是数组本身。线程接收整个数组,但是只能使用其某些位置,例如:
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;
}
我们为每个线程分配一个ID
从到的范围0 to N-1
,N
即线程总数。
为了通知线程,我们可以在线程之间使用共享的原子整数,这些原子将用于更新找到的值的索引。因此,最终代码如下所示:
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);
}
}
输出:
Index of value bigger than 8 : 8
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句