Print Odd and Even Number by Thread using Semaphore

Connect with

Print Odd Even using Semaphore by Thread in JavaLearn how to print odd even using two threads in Java using Semaphore. One thread print even number and 2nd thread print odd mumber using Semaphore.

1. Overview of Two Threads in Java

We know, the order of running of two different threads 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 a sequential fashion using two different threads. It means one thread generates odd numbers and another thread generates even numbers.

2. Overview of Semaphone and its methods

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).

3. Example to print odd even using Semaphore Threads

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 the first is acquired release second when the 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);
		}
	}
}

4. Output of print odd even using two threads in java

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

5. Reference

Visit docs.oracle.com for more details.

I hope you enjoyed this post of print odd even using two threads in java. Visit Core Java tutorial for more details


Connect with

Leave a Comment

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