Can you write a program with 2 threads, in which one prints odd numbers and the other prints even numbers up to

In Java, you can use wait(  ) and notifyAll(  ) to communicate between threads. The code below demonstrates that:


Note: This a typical example of splitting tasks among threads. A method calls notify/notifyAll( ) as the last thing it does (besides return). Since the printOdd( ) and printEven( ) methods were void, the notifyAll( ) was the last statement. If it were to return some value, the notifyAll( ) would have been placed just before the return statement.

Firstly, create the thread classes and the main method that creates the thread and run it.

package multithreading;


public class NumberGenerator extends Thread {


private NumberUtility numberUtility;

private int maxNumber;

private boolean isEvenNumber;



public NumberGenerator(NumberUtility numberUtility, int maxNumber, boolean isEvenNumber) {

this.numberUtility = numberUtility;

this.maxNumber = maxNumber;

this.isEvenNumber = isEvenNumber;



public void run() {

int i = isEvenNumber == true ? 2 : 1;

while (i <= maxNumber) {

if(isEvenNumber == true) {



else {




i = i + 2;





public static void main(String[] args) {

NumberUtility numUtility = new NumberUtility(); //<span id=”IL_AD6″ class=”IL_AD”>single</span> instance shared by oddGen and evenGen threads

final int MAX_NUM = 10;


//create 2 threads, one to generate odd numbers and the other to generate even numbers

NumberGenerator oddGen = new NumberGenerator(numUtility, MAX_NUM, false);

NumberGenerator evenGen = new NumberGenerator(numUtility, MAX_NUM, true);


oddGen.start();  //start the thread – invokes the run() method on NumberGenerator

evenGen.start(); //start the thread – invokes the run() method on NumberGenerator





Next, create the utility class that is used for communicating between the two threads with wait() and notifyAll() methods via synchronized methods.


package multithreading;


import static java.lang.System.out;


public class NumberUtility {


boolean oddPrinted = false;


public synchronized void printOdd(int number) {


while (oddPrinted == true) {

try {

wait();   // waits until notified by even thread


} catch (InterruptedException e) {





out.println(“printOdd() ” + number);

oddPrinted = true;

notifyAll();  //notify all waiting threads




public synchronized void printEven(int number) {

while (oddPrinted == false) {

try {

wait();  //waits until notified by the odd thread


} catch (InterruptedException e) {





oddPrinted = false;

out.println(“printEven() ” + number);

notifyAll();  //notify all waiting threads



The output will be something like:

printOdd() 1

printEven() 2

printOdd() 3

printEven() 4

printOdd() 5

printEven() 6

printOdd() 7

printEven() 8

printOdd() 9

printEven() 10