Reputation: 1
So i have a MaxThread class and the run() method stores the maximum value from the vector passed, into maxValue class attribute. I want to split my initial array of 10 integers into 4 subarrays and each subarray to have a different thread. After i find the 4 maximum values from each one of the 4 subarrays, i want to create a new MaxThread and to display the maximum value from it. this code works but i cant think of a better way to do it as I'm sure what i did is silly( I'm new to this).
public class Main{
public static void main(String[] args) {
int step = 3;
Integer[] vector = new Integer[10];
readFromFile(vector);
int i = 0;
ArrayList<MaxThread> threads = new ArrayList<>();
MaxThread t1 = null;
MaxThread t2 = null;
MaxThread t3 = null;
MaxThread t4 = null;
t1 = new MaxThread(vector, 0, 3);
threads.add(t1);
t1.start();
t2 = new MaxThread(vector, 3, 6);
threads.add(t2);
t2.start();
t3 = new MaxThread(vector, 6, 9);
threads.add(t3);
t3.start();
t4 = new MaxThread(vector, 9, 10);
threads.add(t4);
t4.start();
for (MaxThread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Integer[] last = new Integer[4];
last[0]=t1.getMaxVal();
last[1]=t2.getMaxVal();
last[2]=t3.getMaxVal();
last[3]=t4.getMaxVal();
MaxThread lastThread = new MaxThread(last, 0, last.length);
lastThread.start();
try {
lastThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Valoarea maxima:" +lastThread.getMaxVal());
}
Upvotes: 0
Views: 1991
Reputation: 4604
This is a good case for parallel streams. In general multiple threads are only worth it if you have at least a couple of tens of thousands of elements. In these cases it also pays to have a primitive array.
public static void main(String[] args) {
int[] vector = // ...
int max = Arrays.stream(vector).parallel().max().getAsInt();
}
Upvotes: 1