Answer to Question #249781 in Java | JSP | JSF for amar

Question #249781

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. 


1
Expert's answer
2021-10-11T14:13:37-0400
import java.util.Scanner;


public class App {
	int counter = 1;
	static int maxlimit;


	public int sumEvenNumber() {
		int sum = 0;
		synchronized (this) {
			// Print number till the N
			while (counter < maxlimit) {
				// If count is odd then print
				while (counter % 2 == 1) {
					// Exception handle
					try {
						wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				sum += counter;
				// Increment counter
				counter++;
				// Notify to second thread
				notify();
			}
		}
		return sum;
	}


	public int sumOddNumber() {
		int sum = 0;
		synchronized (this) {
			// Print number till the N
			while (counter <= maxlimit) {


				// If count is even then print
				while (counter % 2 == 0) {


					// Exception handle
					try {
						wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				sum += counter;
				// Increment counter
				counter++;
				// Notify to second thread
				notify();
			}
		}
		return sum;
	}


	static int sumOdd = 0;
	static int sumEven = 0;
	static int sumTotal = 0;


	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		// get the maximum limit from the user
		System.out.print("Enter the maximum limit: ");
		maxlimit = input.nextInt();


		App oep = new App();


		Thread t1 = new Thread(new Runnable() {


			@Override
			public void run() {
				sumEven = oep.sumEvenNumber();


			}
		});
		Thread t2 = new Thread(new Runnable() {


			@Override
			public void run() {
				sumOdd = oep.sumOddNumber();


			}
		});


		t1.start();
		t2.start();


		try {
			t1.join();
			t2.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}


		sumTotal = sumOdd + sumEven;
		System.out.println("The sum of odd numbers: " + sumOdd);
		System.out.println("The sum of even numbers: " + sumEven);
		System.out.println("The sum of odd and even numbers numbers: " + sumTotal);


		input.close();


	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS