Print Odd and Even number in sequence using two threads

One of the interview question on Thread to Print Odd and Even number in sequence using two threads. Below program will print odd and even numbers in sequential order using 2 threads. 1st thread will take care of printing odd numbers and 2nd thread will take care of printing even numbers. Here 1st thread will print odd number and go for waiting state after notifying to 2nd thread to print even number. Next 2nd thread will print even number and go for waiting state after notifying to 1st thread. Its goes on...
Print Odd and Even number in sequence using two threads



class Numbers implements Runnable{

 private int number = 1;

 @Override
 public void run() {
  
  Object lock = Thread.currentThread().getClass();
  
  if(Thread.currentThread().getName().equals("odd")){
   
   synchronized (lock) {
    while(true){
     System.out.println("ODD  : "+number++);
     lock.notify();
     try {
      Thread.sleep(100);// Just to print slowly
      lock.wait();
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
   
  }else{
   synchronized (lock) {
    while(true){
     try {
      Thread.sleep(100);
      lock.wait();
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println("EVEN : " + number++);
     lock.notify();
    }
   } 
  }  
 }
}

public class SequenceNumber {
 
 public static void main(String[] args) throws InterruptedException {
  Numbers obj = new Numbers();

  Thread t1 = new Thread(obj, "even");
  Thread t2 = new Thread(obj, "odd");
  t1.start();
  Thread.sleep(500);
  t2.start();
 } 
}

OUTPUT:

ODD  : 1
EVEN : 2
ODD  : 3
EVEN : 4
ODD  : 5
EVEN : 6
ODD  : 7
EVEN : 8
ODD  : 9
EVEN : 10
ODD  : 11
EVEN : 12
ODD  : 13
EVEN : 14
ODD  : 15
EVEN : 16
ODD  : 17
EVEN : 18
ODD  : 19
EVEN : 20
ODD  : 21
EVEN : 22
ODD  : 23
EVEN : 24
ODD  : 25


No comments :

Post a Comment