In revising for an upcoming exam here is my solution to finding the min value of an array using 2 threads.
I had to create a wrapper for int to pass the minimum value around by reference.
What do you guys think?
public class FindMin {
public static void main(String[] args) {
int[] data = {99,9,14,5,7,33,6,8,21,29,33,44,55,66,77,88,2, 3, 1};
IntObj min = new IntObj(data[0]);
Proc p1 = new Proc(0, (data.length/2)-1, data, min);
Proc p2 = new Proc(data.length/2, data.length, data, min);
p1.start();
p2.start();
try {
p1.join();
p2.join();
}
catch (InterruptedException e) {}
System.out.println("Min value: "+min.value);
}
}
class Proc extends Thread {
int ub, lb;
int[] data;
IntObj min;
public Proc(int lb, int ub, int[] data, IntObj _min) {
this.ub = ub;
this.lb = lb;
this.data = data;
min = _min;
}
public void run() {
for(int i = lb; i < ub; i++) {
compareSet(data[i]);
}
}
public void compareSet(int val) {
synchronized(min) {
if(val < min.value) {
min.value = val;
}
}
}
}
class IntObj {
int value;
public IntObj(int _value) {
value = _value;
}
}
If you have to synchronise for each comparison, any potential gain from using two threads is more than compensated for by the synchronisation overhead. Let each thread find the minimum in its half and write the result to their own output variable. Then compare the two results in the main thread.
And your code will give the wrong result if the minimum is located at
data[data.length/2-1].