In: Computer Science
Write ALL POSSIBLE outputs from the following multithreaded program (10pts). Explain your reasons (10pts).
class Sum{
private int sum;
public int getSum(){
return sum;
}
public void setSum(int sum){
this.sum = sum;
}
}
class Summation implements Runnable{
private int start;
private int end;
private Sum sumValue;
public Summation(int start, int end, Sum sumValue) {
this.start = start;
this.end = end;
this.sumValue = sumValue;
}
public void run(){
int sum = 0;
for(int i=start; i<=end;i++)
sum += i;
sumValue.setSum(sum);
System.out.println(" sum from " + start + " to "+ end + " is " +
sum);
}
}
public class Test{
public static void main(String[] args){
int sum_total=0;
int upper=10;
Sum sumObject1=new Sum();
Sum sumObject2=new Sum();
Thread thrd1=new Thread(new
Summation(1,upper/2-1,sumObject1));
Thread thrd2=new Thread(new
Summation(upper/2,upper,sumObject2));
thrd1.start();
thrd2.start();
try{
thrd1.join();
thrd2.join();
sum_total=sumObject1.getSum() + sumObject2.getSum();
System.out.println("the result is " + sum_total);
}catch (InterruptedException ie) {}
}
}
There are only two possible outputs as shown in the screenshot
either " sum from 1 to 4 " is printed first or "sum from 5 to 10".
Reason --------------------
This happen because of Thread scheduler of JVM(java virtual machine) . If the first Thread get chance to print then "sum from 1 to 4" is printed first , if not then "sum form 5 to 10 " is printed first.