Java Threads Modify the Product class so we can compute the
[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));
}
}
Solution
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);
}
}
![[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). On [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). On](/WebImages/14/java-threads-modify-the-product-class-so-we-can-compute-the-1020002-1761527433-0.webp)
![[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). On [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). On](/WebImages/14/java-threads-modify-the-product-class-so-we-can-compute-the-1020002-1761527433-1.webp)