May 17, 2015

Print Even and Odd number using two different thread

One of the basic question asked in Java interview to check basic understanding of inter thread communication and related threading construct.
In this post we are using synchronisation block and wait()/notify() to print even/odd numbers by two different threads. Another approach to print odd/even number using interruption mechanism.

Below are the sample code which displays even and odd numbers with a time delay of 1 second.
package com.devinline.thread;

public class PrintOddAndEven {

 /**
  * devinline.com
  */
 static volatile int counter = 1;
 static Object object = new Object();// Monitor

 public static void main(String[] args) {
  Thread tEven = new Thread(new EvenProducer(), "Even thread");
  Thread tOdd = new Thread(new OddProducer(), "Odd thread");
  tEven.start();
  tOdd.start();
 }

 static class EvenProducer implements Runnable {
  public void run() {
   synchronized (object) {
    while (true) {
     if (counter % 2 == 0) {
      System.out.println(Thread.currentThread().getName()
        + " produced " + counter);
      try {
       Thread.sleep(1000);
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
      counter++;
      object.notify();
     } else {
      try {
       object.wait();
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     }
    }
   }
  }
 }

 static class OddProducer implements Runnable {
  public void run() {
   synchronized (object) {
    while (true) {
     if (counter % 2 != 0) {
      System.out.println(Thread.currentThread().getName()
        + " produced " + counter);
      counter++;
      object.notify();
     } else {
      try {
       object.wait();
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     }
    }
   }
  }
 }
}
======Sample output=======
Odd thread produced 1
Even thread produced 2
Odd thread produced 3
Even thread produced 4
Odd thread produced 5
Even thread produced 6
Odd thread produced 7
Even thread produced 8
...........
============================
Read also : How to solve above problem using Thread interrupt() - display Even/odd by interrupting thread which is sleeping for a infinite time. 
Location: Hyderabad, Telangana, India