Problem 4. Write a Java program using fork() to compute average of N numbers. Th
ID: 3542890 • Letter: P
Question
Problem 4. Write a Java program using fork() to compute average of N numbers. The parent process forks a child process that takes input from the user, adds all the numbersand returns the sum and the count of numbers to the parent process that divides the sum
by the count of the number, and prints out the average. Problem 4. Write a Java program using fork() to compute average of N numbers. The parent process forks a child process that takes input from the user, adds all the numbers
and returns the sum and the count of numbers to the parent process that divides the sum
by the count of the number, and prints out the average.
Explanation / Answer
import java.util.Scanner;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class Sum extends RecursiveTask<Integer> {
private final int num;
public Sum(int num) {
this.num=num;
}
@Override
protected Integer compute() {
int sum=0;
for(int i=1;i<=num;i++){sum+=i;}
return sum;
}
public static void main(String[] args) {
// create a random data set
System.out.println("enter n : ");
Scanner in=new Scanner(System.in);
int temp=in.nextInt();
// submit the task to the pool
final ForkJoinPool pool = new ForkJoinPool(4);
final Sum finder = new Sum(temp);
System.out.println( "the average is : "+pool.invoke(finder)/(double)temp);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.