Computer scienceProgramming languagesJavaWorking with dataMultithreadingSynchronization

CountDownLatch

Integral

Report a typo

You are given a function f(x) = x^2. Your task is to calculate the integral of this function within a given interval [a, b] using the rectangle method and multithreading. The integral must be calculated as the sum of the areas of many small rectangles. The width of each rectangle is (b - a) / n, where n is the number of rectangles (and also the number of threads).

The main thread must wait until all calculations are completed before it continues execution.

The input parameters are a, b, and n. The output is the total area under the curve of this function.

Sample Input 1:

1
5
4

Sample Output 1:

41.0
Write a program in Java 17
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

class IntegralCalculator implements Runnable {
private final double a, b;
private final AtomicReference<Double> totalArea;
private final CountDownLatch latch;

public IntegralCalculator(double a, double b, AtomicReference<Double> totalArea, CountDownLatch latch) {
this.a = a;
this.b = b;
this.totalArea = totalArea;
this.latch = latch;
}

@Override
public void run() {
double width = ...
// The height of the rectangle is the value of the function at the midpoint
double height = ...
// f(x) = x^2
double area = ...

totalArea.accumulateAndGet(area, Double::sum);

// decrease count of latch here
...
}
}

public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double a = scanner.nextDouble();
double b = scanner.nextDouble();
int n = scanner.nextInt();

AtomicReference<Double> totalArea = new AtomicReference<>(0.0);
CountDownLatch latch = new CountDownLatch(n);

double width = (b - a) / n;
for (int i = 0; i < n; i++) {
double x1 = a + width * i;
double x2 = x1 + width;
new Thread(new IntegralCalculator(x1, x2, totalArea, latch)).start();
}

try {
// wait
...
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(totalArea.get());
}
}
___

Create a free account to access the full topic