我已经编写了使用多线程计算给定数组中的最小和最大数字的代码。这个想法与binarysearch
类似,我只是将数组分成两半并计算每一半的最小值和最大值,并相应地更新我的最小值和最大值字段。
对于多线程来说,这可能是一个愚蠢的例子。但既然我想到了这个,我就想实现一下,看看进展如何。到目前为止,代码令人惊讶地工作正确。我预计它不会给出正确的结果,因为我没有等待第一个线程完成,而是立即启动第二个线程。这意味着最小值和最大值一定没有正确更新。
有人可以指出为什么它在多次运行中可以正常工作以及任何改进的空间。
代码在这里
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class MinMax implements Runnable{
Long min=Long.MAX_VALUE;
Long max=Long.MIN_VALUE;
int low;
int high;
Long[] arr;
public MinMax(int low, int high, Long[] arr){
this.low = low;
this.high=high;
this.arr = arr;
}
@Override
public void run() {
System.out.println("called run ");
if (low-high<=2){
System.out.println("called ");
List<Long> l = Arrays.asList(arr);
min=Collections.min(l) < min ? Collections.min(l) : min;
max=Collections.max(l) > max ? Collections.max(l) : max;
}
else {
System.out.println(Thread.currentThread());
int mid = (high+low)/2;
MinMax left = new MinMax(low,mid,arr);
MinMax right = new MinMax(mid,high,arr);
Thread t1 = new Thread(left);
Thread t2 = new Thread(right);
t1.start();
t2.start();
Set<Thread> threadset=Thread.getAllStackTraces().keySet();
for (Thread t : threadset)
System.out.println(t.getName());
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
long[] arr = {3,4,5,1123,567,78,90,5,35434,1,34,56,111,2,56,789,87645,343535};
Long[] newarr= new Long[arr.length];
int i = 0;
for (long temp : arr)
newarr[i++]=temp;
MinMax m = new MinMax(0,arr.length,newarr);
m.run();
System.out.println(m.min);
System.out.println(m.max);
}
}
最佳答案
为什么它有效?第一次low
是 0
和high
大约是18
。 low-high<=2
是 true 并且您的线程代码不会被调用。无论如何,线程代码不会产生任何结果。
ForkJoinPool
旨在为您处理此类事情。
关于java - Java中多线程计算最小和最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20409836/