I have a trouble getting the proper value in the end of the function. I cannot understand how to make the main thread to wait for executor to finish, so I can display the proper value.
Each task calculates the product of values at index i in the arrays. I set the product variable to be volatile and synchronized the fucntion calculating the product to make sure that only one thread gets access to it and modifies it. But I cannot arrange the threads to wait to for executor to finish and then show the answer.
 public class NewBetterDot {
static double[] vectorOne;
static double[] vectorTwo;
private static volatile double product;;
public NewBetterDot(double[] vectorOne, double[] vectorTwo, double product) {
    super();
    this.vectorOne = vectorOne;
    this.vectorTwo = vectorTwo;
    this.product = product;
}
public static synchronized double smallDot(int i) {
    double multi = vectorOne[i] * vectorTwo[i];
    return multi;
}
static class Task implements Runnable {
    int i;
    @Override
    public void run() {
        // System.out.println("Before operation: " + product);
        product = product + NewBetterDot.smallDot(i);
        System.out.println(Thread.currentThread().getName() + " Product is equal to: " + product);
    }
    public Task(int i) {
        super();
        this.i = i;
    }
}
static class PrintTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Product equals to: " + product);
    }
}
public static void main(String[] args) throws NullPointerException {
    double sum = 0.0;
    NewBetterDot objectOne = new NewBetterDot(new double[] { 5.0, 4.0, 1.0 }, new double[] { 1.0, 2.0, 3.0 }, 0.0);
    int threshhold = vectorOne.length;
    ExecutorService executor = Executors.newFixedThreadPool(2);
    ;
    for (int i = 0; i < threshhold; i++) {
        NewBetterDot.Task task = new NewBetterDot.Task(i);
        executor.submit(task);
    }
    executor.shutdown();
    NewBetterDot.PrintTask pt = new NewBetterDot.PrintTask();
    pt.run();
}
}
Blockquote
 
     
     
    