Saturday, April 7, 2018

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

In this post we'll see a Java program which prints 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

Recommendations for learning

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

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 - Java Program
  4. How to Create Deadlock in Java Multi-Threading - Java Program
  5. Producer-Consumer Java Program Using volatile

You may also like -

  1. How to Create Your Own BlockingQueue - Java Program
  2. Getting All The Schemas in a DB - Java Program
  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 multithreading
  7. Method reference in Java 8
  8. Spring example program using JavaConfig and Annotations