Print Odd And Even Numbers By Two Threads In Java

Odd And Even Numbers By Two Threads Java Program :

Write a java program where two threads print odd and even numbers in sync. That means, one thread should print only the odd numbers and another thread should print only the even numbers. But, both threads should communicate with each other so that numbers should be printed in natural order.

Sample Output :

Odd-Thread : 1
Even-Thread : 2
Odd-Thread : 3
Even-Thread : 4
Odd-Thread : 5
Even-Thread : 6

How To Print Odd And Even Numbers By Two Threads In Java?

The task of printing odd and even numbers by two threads in sync can be divided in 4 steps. Let’s see those steps one by one.

Step 1 : Odd Thread

The task of this thread is to print only the odd numbers. OddThread internally calls printOdd()method of SharedPrinter class (We will see SharedPrinter class in step 3).

//OddThread to print odd numbers
//Calls printOdd() method of SharedPrinter class until limit is exceeded.

class OddThread extends Thread {
	int limit;

	sharedPrinter printer;

	public OddThread(int limit, sharedPrinter printer) {
		this.limit = limit;

		this.printer = printer;
	}

	@Override
	public void run() {
		int oddNumber = 1; // First odd number is 1

		while (oddNumber <= limit) {
			printer.printOdd(oddNumber); // Calling printOdd() method of
											// SharedPrinter class

			oddNumber = oddNumber + 2; // Incrementing to next odd number
		}
	}
}

Step 2 : Even Thread

The task of this thread is to print only the even numbers. EvenThread internally calls printEven()method of SharedPrinter class (See SharedPrinter class in step 3)

// EvenThread to print even numbers.
// Calls printEven() method of SharedPrinter class until limit is exceeded.

class EvenThread extends Thread {
	int limit;

	sharedPrinter printer;

	public EvenThread(int limit, sharedPrinter printer) {
		this.limit = limit;

		this.printer = printer;
	}

	@Override
	public void run() {
		int evenNumber = 2; // First even number is 2

		while (evenNumber <= limit) {
			printer.printEven(evenNumber); // Calling printEven() method of
											// SharedPrinter class

			evenNumber = evenNumber + 2; // Incrementing to next even number
		}
	}
}

Step 3 : SharedPrinter Class.

This class is at the core of the whole task. In this class, both threads – OddThread and EvenThread– communicate with each other using wait() and notify() to print odd and even numbers in sync. This class has three members. 
1) A boolean variable, isOddPrinted : It stores the status whether odd number is printed or not. 
2) printOdd() Method : This method is called by OddThread. First, it checks the status isOddPrinted. If isOddPrinted is true then it waits until next even number is printed by EvenThread. If isOddPrinted is false then it prints next odd number, sets isOddPrinted to true and notifies EvenThread
3) printEven() Method : This method is called by EvenThread. First, it checks the status of isOddPrinted. If isOddPrinted is false then it waits until next odd number is printed by OddThread. If isOddPrinted is true then it prints next even number, sets isOddPrinted to false and notifies OddThread.

class sharedPrinter {
	// A boolean flag variable to check whether odd number is printed or not
	// Initially it is false.

	boolean isOddPrinted = false;

	// synchronized printOdd() method to print odd numbers. It is executed by
	// OddThread.
	// First checks isOddPrinted,
	// if isOddPrinted is true then it waits until next even number is printed
	// by EvenThread
	// If isOddPrinted is false then prints next odd number, sets isOddPrinted
	// to true

	synchronized void printOdd(int number) {
		if (isOddPrinted) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println(Thread.currentThread().getName() + " : " + number);

		isOddPrinted = true;

		notify();
	}

	// Synchronized printEven() method to print even numbers. It is executed by
	// EvenThread.
	// First checks isOddPrinted,
	// if isOddPrinted is false then it waits until next odd number is printed
	// by OddThread
	// If isOddPrinted is true then it prints next even number, sets
	// isOddPrinted to false

	synchronized void printEven(int number) {
		if (!isOddPrinted) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println(Thread.currentThread().getName() + " : " + number);

		isOddPrinted = false;

		notify();
	}
}

Step 4 : Main Class

In the MainClass, we instantiate OddThread and EvenThread by passing limit and SharedPrinterobject, give them the name and start both the threads.

public class MainClass 
{
    public static void main(String[] args) 
    {
        sharedPrinter printer = new sharedPrinter();
         
        OddThread oddThread = new OddThread(20, printer);
         
        oddThread.setName("Odd-Thread");
         
        EvenThread evenThread = new EvenThread(20, printer);
         
        evenThread.setName("Even-Thread");
         
        oddThread.start();
         
        evenThread.start();
    }
}

Above 4 steps can be represented pictorially as follows

Full Java Program To Print Odd And Even Numbers By Two Threads :

//OddThread to print odd numbers
//Calls printOdd() method of SharedPrinter class until limit is exceeded.

class OddThread extends Thread {
	int limit;

	sharedPrinter printer;

	public OddThread(int limit, sharedPrinter printer) {
		this.limit = limit;

		this.printer = printer;
	}

	@Override
	public void run() {
		int oddNumber = 1; // First odd number is 1

		while (oddNumber <= limit) {
			printer.printOdd(oddNumber); // Calling printOdd() method of
											// SharedPrinter class

			oddNumber = oddNumber + 2; // Incrementing to next odd number
		}
	}
}

// EvenThread to print even numbers.
// Calls printEven() method of SharedPrinter class until limit is exceeded.

class EvenThread extends Thread {
	int limit;

	sharedPrinter printer;

	public EvenThread(int limit, sharedPrinter printer) {
		this.limit = limit;

		this.printer = printer;
	}

	@Override
	public void run() {
		int evenNumber = 2; // First even number is 2

		while (evenNumber <= limit) {
			printer.printEven(evenNumber); // Calling printEven() method of
											// SharedPrinter class

			evenNumber = evenNumber + 2; // Incrementing to next even number
		}
	}
}

class sharedPrinter {
	// A boolean flag variable to check whether odd number is printed or not
	// Initially it is false.

	boolean isOddPrinted = false;

	// synchronized printOdd() method to print odd numbers. It is executed by
	// OddThread.
	// First checks isOddPrinted,
	// if isOddPrinted is true then it waits until next even number is printed
	// by EvenThread
	// If isOddPrinted is false then prints next odd number, sets isOddPrinted
	// to true

	synchronized void printOdd(int number) {
		if (isOddPrinted) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println(Thread.currentThread().getName() + " : " + number);

		isOddPrinted = true;

		notify();
	}

	// Synchronized printEven() method to print even numbers. It is executed by
	// EvenThread.
	// First checks isOddPrinted,
	// if isOddPrinted is false then it waits until next odd number is printed
	// by OddThread
	// If isOddPrinted is true then it prints next even number, sets
	// isOddPrinted to false

	synchronized void printEven(int number) {
		if (!isOddPrinted) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println(Thread.currentThread().getName() + " : " + number);

		isOddPrinted = false;

		notify();
	}
}

// Main Class

public class MainClass {
	public static void main(String[] args) {
		sharedPrinter printer = new sharedPrinter();

		OddThread oddThread = new OddThread(20, printer);

		oddThread.setName("Odd-Thread");

		EvenThread evenThread = new EvenThread(20, printer);

		evenThread.setName("Even-Thread");

		oddThread.start();

		evenThread.start();
	}
}

Output :

Odd-Thread : 1
Even-Thread : 2
Odd-Thread : 3
Even-Thread : 4
Odd-Thread : 5
Even-Thread : 6
Odd-Thread : 7
Even-Thread : 8
Odd-Thread : 9
Even-Thread : 10
Odd-Thread : 11
Even-Thread : 12
Odd-Thread : 13
Even-Thread : 14
Odd-Thread : 15
Even-Thread : 16
Odd-Thread : 17
Even-Thread : 18
Odd-Thread : 19
Even-Thread : 20

One thought on “Print Odd And Even Numbers By Two Threads In Java

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.