Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Please screen of the execution of the program in addition to the source code. For the following code import java.math.BigInteger; import java.util.Scanner; class SumThread extends
Please screen of the execution of the program in addition to the source code.
For the following code
import java.math.BigInteger;
import java.util.Scanner;
class SumThread extends Thread {
public SumThread (BigInteger from, BigInteger to) {
this.from = from;
this.to = to;
sum = new BigInteger("0");
}
public void run( ) {
for(BigInteger i = from; i.compareTo(to) <= 0; i = i.add(new BigInteger("1"))) {
sum = sum.add(i);
}
}
public BigInteger getSum( ) {
return sum;
}
private BigInteger from, to, sum;
}
public class Sum4 {
public static void main(String args[]) {
/*if(args.length != 3) {
System.out.println("Pass threads, start and end.");
return;
}*/
Scanner s=new Scanner(System.in);
System.out.print("Enter The Number Of Threads: ");
/* get arguments */
int num_threads = s.nextInt();
System.out.print("Enter The Starting Number : ");
BigInteger from = new BigInteger(String.valueOf(s.nextInt()));
System.out.print("Enter The Ending Number : ");
BigInteger to = new BigInteger(String.valueOf(s.nextInt()));
/* an array of threads */
SumThread [] threads = new SumThread [num_threads];
/* fill in the start/end ranges for each */
BigInteger step = to.subtract(from).divide(BigInteger.valueOf(num_threads));
long startTime = System.currentTimeMillis();
for(int i = 0; i < num_threads; i++) {
BigInteger start = from.add(step.multiply(BigInteger.valueOf(i)));
BigInteger stop = start.add(step).subtract(BigInteger.valueOf(1));
/* make sure we go all the way to the end on last thread */
if(i == (num_threads - 1)) {
stop = to;
}
System.out.printf("Thread %s sums from %s to %s. ", i, start.toString( ), stop.toString( ));
threads[i] = new SumThread (start, stop);
}
/* start them all */
for(int i = 0; i < num_threads; i++) {
threads[i].start( );
}
/* wait for all the threads to finish! */
try {
for(int i = 0; i < num_threads; i++) {
threads[i].join( );
}
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
/* calculate total sum */
BigInteger total_sum = new BigInteger("0");
for(int i = 0; i < num_threads; i++) {
total_sum = total_sum.add(threads[i].getSum( ));
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.printf("The sum of %s-%s is %s in total time %d msec. ", from.toString( ), to.toString( ), total_sum.toString( ),elapsedTime);
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started