Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

[Java] [Threads] Modify the Product class so we can compute the product of the e

ID: 3932813 • Letter: #

Question

[Java] [Threads] Modify the Product class so we can compute the product of the elements of the data array using two threads (in addition to the main thread). One thread should compute the product of the first half of the array and the second one will take care of the rest. Make sure your code has no data races.

public class Product {

    public int[] data;

    public Product(int[] data) {

        this.data = data;

    }

    public int computeProduct(int startIndex, int endIndex) {

        int result = 1;

        for (int i = startIndex; i <= endIndex; i++) {

            result *= data[i];

        }

        return result;

    }

    public static void main(String[] args) {

        int[] data = {2, 3, 4, 2, 2, 3};

        Product product = new Product(data);

        System.out.println(product.computeProduct(0, 5));

    }

}

Explanation / Answer

import java.util.*;
import java.lang.*;
import java.io.*;

public class Product extends Thread {

public int[] data;
public static int result;


public Product(int[] data) {
this.data = data;
}
public void run(){
  
  
  
result = 1;
  
for (int i=0; i < data.length/2; i++) {
result *= data[i];

}
System.out.println(result);
  
  
  
}


public void run(int res){
  

  
result = res;
for (int i=data.length/2; i < data.length; i++) {
result *= data[i];
}
System.out.println(result);
  
  
  
}

public static void main(String[] args) {
int[] data = {2, 3, 4, 2, 2, 3};

  
Product t1 = new Product(data);
t1.run();
  

  
Product t2 = new Product(data);
t2.run(1);
  
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote