In: Computer Science
// ArithmeticSeries class that implements Runnable
interface
// and calculate sum from start to end by taking parameters through
constructor
class ArithmeticSeries implements Runnable{
private volatile int sum = 0;
private int start, end;
// get start and end
public ArithmeticSeries(int s, int e){
start = s;
end = e;
}
// get sum
@Override
public void run() {
calculateSum();
}
// calculate sum by looping from start to end and adding it to
sum
public void calculateSum() {
try{
for(int i = start; i <= end;
i++){
sum = sum + i;
}
}catch (Exception e){
}
}
// return calculated result sum
public int getSum(){
return sum;
}
}
public class ArithmeticSeriesTest{
public static void main(String args[]){
// create two ArithmeticSeries object by passing
1-100 & 101-200 to each object
ArithmeticSeries as1 = new ArithmeticSeries(1,
100);
ArithmeticSeries as2 = new ArithmeticSeries(101,
200);
// create two threads from main thread by
passing ArithmeticSeries object
Thread t1 = new Thread(as1);
Thread t2 = new Thread(as2);
// start executing threads
t1.start();
t2.start();
// join threads so that each thread can
report main thread about exit
try{
t1.join();
t2.join();
}catch(Exception e){}
// collect result from both threads and
compute final sum
int as1_sum = as1.getSum();
int as2_sum = as2.getSum();
int total = as1_sum + as2_sum;
System.out.println("sum:- " + total);
}
}