Print even and odd numbers using threads in java

Problem: How to print even and odd numbers using threads in Java? Two threads should be used to print numbers. One thread should print even numbers and other should print odd numbers. Numbers should be printed sequentially .i.e. 1, 2, 3, 4..

This program was asked in makeMyTrip interview. You need to have clear understanding of inter-thread communication to solve this problem.

We will use two threads to print even and odd numbers. Threads use wait, notify and notifyAll to communicate with each other. In this case we will be using wait and notify for inter-thread communication.

wait() – Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

notify() – Wakes up a single thread that is waiting on this object’s monitor.

synchronized – synchronized keyword is used to get lock on an object.

Java program:

We are using two threads to print even and odd numbers. Following is the mechanism to print even and odd numbers using threads in Java.

There are 2 threads, EvenThread and OddThread.
These 2 threads are trying to get lock on Printer object.

We use a boolean variable isEvenPrinted to check if even number is
printed or not.
isEvenPrinted is initialized to true

If EvenThread get lock on Printer  // synchronized
   If isEvenPrinted is true
      wait for OddThread to print  // Lock on Printer is released
   End If
   
   // Once the odd number is printed. Lock on Printer is acquired.
   print even number
   set isEvenPrinted to false
   Notify OddThread that it is done // Lock on Printer is released
End if

If OddThread get lock on Printer  // synchronized
   If isEvenPrinted is false
      wait for EvenThread to print  // Lock on Printer is released
   End If
   
   // Once the even number is printed. Lock on Printer is acquired.
   Print oddnumber
   Set isEvenPrinted to true
   Notify EvenThread that it is done // Lock on Printer is released
End if

We will put above mechanism in Java code. Let us see how to print even and odd numbers using threads in Java. We will print numbers from 1 to 10.

package com.javafries.thread;

public class EvenOddNumberPrinter {

	private static class NumberPrinter {

		// To check if even number is printed or not.
		private boolean isEvenPrinted = true;

		public void printOdd(int number) throws InterruptedException {
			// Get a lock on NumberPrinter
			synchronized (this) {

				// Wait until even is not printed.
				if (!isEvenPrinted)
					wait();

				System.out.println(number);

				isEvenPrinted = false;

				// Notify the other waiting thread which is waiting on
				// NumberPrinter
				// Other thread will get out of waiting state
				notify();
			}
		}

		public void printEven(int number) throws InterruptedException {
			synchronized (this) {
				if (isEvenPrinted)
					wait();

				System.out.println(number);
				isEvenPrinted = true;
				notify();
			}
		}
	}

	private static class OddNumberGenerator implements Runnable {
		private NumberPrinter q;
		private int max;

		public OddNumberGenerator(NumberPrinter q, int max) {
			this.q = q;
			this.max = max;
		}

		@Override
		public void run() {
			for (int i = 1; i < max; i = i + 2) {
				try {
					q.printOdd(i);
				} catch (InterruptedException ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	private static class EvenNumberGenerator implements Runnable {
		private NumberPrinter printer;
		private int max;

		public EvenNumberGenerator(NumberPrinter printer, int max) {
			this.printer = printer;
			this.max = max;
		}

		@Override
		public void run() {
			for (int i = 2; i <= max; i = i + 2) {
				try {
					printer.printEven(i);
				} catch (InterruptedException ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		int maxNumber = 10;
		NumberPrinter printer = new NumberPrinter();

		new Thread(new EvenNumberGenerator(printer, maxNumber)).start();
		new Thread(new OddNumberGenerator(printer, maxNumber)).start();
	}
}

In above program we are using a shared Printer object.

Output:

1
2
3
4
5
6
7
8
9
10

Hope you understood above solution to print even and odd numbers using threads in Java. It is very important understand wait() and notify() to understand inter-thread communication.
Your question and comments are most welcome.

2 Comments

  1. Ish July 18, 2016
    • Vkp June 28, 2017

Leave a Reply