Tuesday, April 6, 2021

Print Odd-Even Numbers Using Threads And wait-notify Java Program

In this post we'll see a Java program to print odd and even numbers sequentially using two threads. One thread generates odd numbers and another even numbers. This Java program makes use of inter-thread communication using wait, notify, notifyAll to print odd-even numbers.

Java program to print odd-even numbers using threads

There is a class SharedPrinter whose object is shared between two threads. In this class there is a method printEvenNum() for printing even numbers and method printOddNum() for printing odd numbers.

These two methods are called by the respective threads EvenNumProducer and OddNumProducer and these threads communicate using wait and notify, of course from inside a synchronized block.

public class EvenOddThreadDemo {
  public static void main(String[] args) {
    // shared class object
    SharedPrinter sp = new SharedPrinter();
    // creating two threads
    Thread t1 = new Thread(new EvenNumProducer(sp, 10));
    Thread t2 = new Thread(new OddNumProducer(sp, 10));
    // starting threads
    t1.start();
    t2.start();
  }
}
// Shared class used by both threads
class SharedPrinter{
  boolean evenFlag = false;
 
  //Method for printing even numbers
  public void printEvenNum(int num){
    synchronized (this) {
      // While condition as mandated to avoid spurious wakeup
      while(!evenFlag){
        try {
          //asking current thread to give up lock
          wait();
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      System.out.println(num);
      evenFlag = false;
      // Wake up thread waiting on this monitor(lock)
      notify();
    }
  }
 
  //Method for printing odd numbers
  public void printOddNum(int num){
    synchronized (this) {
      // While condition as mandated to avoid spurious wakeup
      while(evenFlag){
        try {
         //asking current thread to give up lock
         wait();
        } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }
      }
      System.out.println(num);
      evenFlag = true;
      // Wake up thread waiting on this monitor(lock)
      notify();   
    }
  }
}

// Thread Class generating Even numbers
class EvenNumProducer implements Runnable{
  SharedPrinter sp;
  int index;
  EvenNumProducer(SharedPrinter sp, int index){
    this.sp = sp;
    this.index = index;
  }
  @Override
  public void run() {
    for(int i = 2; i <= index; i = i+2){
      sp.printEvenNum(i);
    }   
  }   
}

//Thread Class generating Odd numbers
class OddNumProducer implements Runnable{
  SharedPrinter sp;
  int index;
  OddNumProducer(SharedPrinter sp, int index){
    this.sp = sp;
    this.index = index;
  }
  @Override
  public void run() {
    for(int i = 1; i <= index; i = i+2){
      sp.printOddNum(i);
    }
  }
}

Output

1
2
3
4
5
6
7
8
9
10

That's all for this topic Print Odd-Even Numbers Using Threads And wait-notify Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  2. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  3. How to Run Threads in Sequence in Java
  4. How to Create Deadlock in Java
  5. Producer-Consumer Java Program Using volatile

You may also like-

  1. Java Program to Create Your Own BlockingQueue
  2. Java Program to Get All DB Schemas
  3. Count Number of Words in a String Java Program
  4. How to Convert Date And Time Between Different Time-Zones in Java
  5. Marker interface in Java
  6. Synchronization in Java - Synchronized Method And Block
  7. Method Reference in Java
  8. Spring Java Configuration Example Using @Configurations