top of page

Print Alternatively numbers from two different thread using java (java Interview Question)

Question is to execute one task from one thread and then wait and notify another thread to work

public static void main(String[] agrs){
         Printer p = new Printer();

		Runnable r1 = () -> {
			for (int i = 0; i <= 10; i++) {
				if (i % 2 == 0)
					p.printEven(i);
			}
		};
		Runnable r2 = () -> {
			for (int i = 0; i <= 10; i++) {
				if (i % 2 != 0)
					p.printOdd(i);
			}
		};
		Thread t1 = new Thread(r1);
		Thread t2 = new Thread(r2);
		t1.start();
		t2.start();

}


class Printer {
	private boolean evenTrue = true;

	public synchronized void printEven(int number) {
		while (!evenTrue) {
			try {
				wait();
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
		}
		System.out.print(number + " ");
		evenTrue = false;
		notify();
	}

	public synchronized void printOdd(int number) {
		while (evenTrue) {
			try {
				wait();
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
		}
		System.out.print(number + " ");
		evenTrue = true;
		notify();
	}
}

Recent Posts

See All

Comments


Call 

7869617359

Email 

Follow

  • Facebook
  • Twitter
  • LinkedIn
  • Instagram
Never Miss a Post. Subscribe Now!

Thanks for submitting!

bottom of page