Name - Sanjay Nithin S
Reg No. - 20BIT0150
2. Write a multithreading program to get the maximum limit from the user to find the
sum of odd and even numbers. Create a thread to find the even numbers from 1 to the
maxlimit and get the summation. Similarly create another thread to find the odd
numbers from 1 to maxlimit and get the summation. In the main thread the summation
of both the odd sum and even sum should be calculated.
Code:
import java.util.Scanner;
class newFie {
int x =0;
int evensum = 0;
int oddsum = 0;
static int N;
public void SummationOfEven() {
synchronized (this) {
while (x < N) {
while (x % 2 == 0) {
evensum = evensum + x;
System.out.println("Even " + x);
try {
wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
x++;
notify();
}
}
System.out.println("Even : " + evensum);
}
public void SummationOfOdd() {
synchronized (this) {
while (x < N) {
while (x % 2 == 1) {
oddsum = oddsum + x;
System.out.println("Odd " + x);
try {
wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
x++;
notify();
}
}
System.out.println("Odd : " + oddsum);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
newFie obj = new newFie();
Thread t1 = new Thread(new Runnable() {
public void run() {
obj.SummationOfEven();
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
obj.SummationOfOdd();
}
});
t1.start();
t2.start();
sc.close();
}
}
Output :