This bit of code initializes an array of any given size where each index corresponds to a thread and a value. That is, index 0 has 0, index 1 has 1, and so on. Then, the values, 0 to n, in the indexes are summed.
This code as part of an assignment though I'm wondering if there are any ways it could be improved? Namely, is there an alternative to using 2 for loops and calling thread.join() on them?
I'd be open to any advice and would gladly take it!
public class Processor { static volatile int numberOfValues = 17; static double processedArray[]; static Thread threadsArray[]; static volatile int sum; static Object lock1 = new Object(); static Object lock2 = new Object();
Adding values to the array, each index in the array gets a thread to initialize that value:
private static void initializeArray() { threadsArray = new Thread[numberOfValues]; processedArray = new double[numberOfValues]; for (int i = 0; i < threadsArray.length; i++) { threadsArray[i] = new Thread(new Runnable() { public void run() { synchronize(lock1) { processedArray[numberOfValues - 1] = numberOfValues; numberOfValues--; } } }); threadsArray[i].start(); }
Here is the first for loop joining all threads after the initialization of the array:
for (int i = 0; i < threadsArray.length; i++) { try { threadsArray[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } }
Summing the values in the array:
for (int i = 0; i < threadsArray.length; i++) { threadsArray[i] = new Thread(new Runnable() { public void run() { synchronize(lock2) { sum += processedArray[numberOfValues]; numberOfValues++; } } }); threadsArray[i].start(); }
Here is the second for loop joining all the threads after summing:
for (int i = 0; i < threadsArray.length; i++) { try { threadsArray[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Main:
public static void main(String args[]) { initializeArray(); for (int i = 0; i < threadsArray.length; i++) { System.out.println(processedArray[i]); } System.out.println("Sum: " + sum); } }