How to Print Odd and Even Number by Thread using Semaphore

Connect with

Oracle Java
We know order of running of two different thread is not in our hand by default but somewhere we need to control the order of running. So I tried to demonstrate inter thread communication by using Semaphore. This Java program prints odd & even numbers in sequential fashion using two different threads. It means one thread generates odd numbers and another thread generate even numbers.

This program demonstrate inter thread communication using Semaphore which is available in java.util.concurrent package. The Semaphore conceptually, maintains a set of permits. Semaphore class has two methods that make use of permits:

  • acquire(): Acquires a permit from this semaphore, blocking until one is available, or the thread is interrupted. It has another overloaded version acquire(int permits).
  • release() : Releases a permit, returning it to the semaphore. It has another overloaded method release(int permits).

In the Java program there is class SharedPrinter whose object is shared between two threads. In this class there is a method printEvenNumber() for printing even numbers and method printOddNumber() for printing odd numbers.

These two methods are called by the respective threads EvenNumberThread and OddNumberThread and these threads communicate using semaphore. Idea is to have 2 semaphores when first is acquired release second, when second is acquired release first. That way shared resource has controlled access and there is inter-thread communication between the threads.

Note: one of the semaphore evenSemaphore is initialized with 0 permits that will make sure that even number generating thread doesn’t start first.


package com.mysoftkey.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * This demo class is used about inter process of thread communication demo. 
 * e.g one thread print Odd number and another thread print even no by using Semaphore
 * 
 * @author ranjeet jha
 *
 */
public class EvenOddDisplayBySemaphore {

	public static void main(String[] args) {
		SharedPrinter printer = new SharedPrinter();
		
		System.out.println("two different threads to print odd and even number upto max provided, starting from  1 : ");
		// Starting two threads
		ExecutorService executor = Executors.newFixedThreadPool(2);
		executor.execute(new EvenNumberThread(printer, 10));
		executor.execute(new OddNumberThread(printer, 10));
		executor.shutdown();
	}

}

SharedPrinter.java: Which print even and odd number

/**
 * This is main class which acquire and release lock on respective semaphore.
 * And this class is used to print odd and even no sequential manner by two different thread.
 * 
 * @author ranjeet jha
 *
 */
class SharedPrinter {
	boolean evenFlag = false;
	
	// creating instance of 2 semaphores , one is for even and another for odd
	Semaphore evenSemaphore = new Semaphore(0);
	Semaphore oddSemaphore = new Semaphore(1);

	/**
	 * Method for printing even numbers
	 * 
	 * @param num
	 */
	public void printEvenNumber(int num) {
		try {
			evenSemaphore.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(num);
		oddSemaphore.release();
	}

	// Method for printing odd numbers
	public void printOddNum(int num) {
		try {
			oddSemaphore.acquire();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(num);
		evenSemaphore.release();

	}
}

/**
 * This class is responsible to generate Even number
 * 
 * @author ranjeet jha
 *
 */
class EvenNumberThread implements Runnable {
	SharedPrinter sp;
	int maxNumberTobePrint;

	EvenNumberThread(SharedPrinter sp, int index) {
		this.sp = sp;
		this.maxNumberTobePrint = index;
	}

	@Override
	public void run() {
		for (int i = 2; i <= maxNumberTobePrint; i = i + 2) {
			sp.printEvenNumber(i);
		}

	}

}


/**
 * This class is responsible to generate Odd number
 * @author ranjeet
 *
 */
class OddNumberThread implements Runnable {
	SharedPrinter printer;
	int maxNumberTobePrint;

	OddNumberThread(SharedPrinter sp, int index) {
		this.printer = sp;
		this.maxNumberTobePrint = index;
	}

	@Override
	public void run() {
		for (int i = 1; i <= maxNumberTobePrint; i = i + 2) {
			printer.printOddNum(i);
		}
	}
}

Output


two different threads to print odd and even number upto max provided, starting from  1 : 
1
2
3
4
5
6
7
8
9
10

Connect with

Leave a Reply

Your email address will not be published. Required fields are marked *