Java Semaphore - Print Alternate Numbers Sequence Using Three Threads
In this example we will be implementing multiple threads to print alternate values of sequence.
So here thread1 will print 1,4,7 thread2 will print 2,5,8 thread3 will print 3,6,9.
Semaphore - Table Of Contents
Understanding Java Semaphore Java Semaphore - Print even and odd numbers using Threads Java Semaphore - Print numbers sequence using three Threads
Step 1 - Thread 1 gets the permit for semaphore1 to print one sequence numbers
Step 2 - Thread 1 releases permit for semaphore2
Step 3 - Thread 2 gets the permit for semaphore1 to print two sequence numbers
Step 4 - Thread 2 releases permit for semaphore3
Step 5 - Thread 3 gets the permit for semaphore1 to print three sequence numbers
Step 6 - Thread 3 releases permit for semaphore1
Step 7 - Thread 1 gets the permit for semaphore1 to print one sequence numbers
package com.javastructures; import java.util.concurrent.Semaphore; public class SemaphoreExample { public static void main(String[] args) { Semaphore one = new Semaphore(1); Semaphore two = new Semaphore(0); Semaphore three = new Semaphore(0); PrintOneNumber printOneNumber = new PrintOneNumber(one, two); PrintTwoNumber printTwoNumber = new PrintTwoNumber(two, three); PrintThreeNumber printThreeNumber = new PrintThreeNumber(three, one); new Thread(printOneNumber, "Print one").start(); new Thread(printTwoNumber, "Print two").start(); new Thread(printThreeNumber, "Print three").start(); } } class PrintOneNumber implements Runnable { Semaphore sempahoreOne; Semaphore sempahoreTwo; public PrintOneNumber(Semaphore sempahoreOne, Semaphore sempahoreTwo) { super(); this.sempahoreOne = sempahoreOne; this.sempahoreTwo = sempahoreTwo; } @Override public void run() { for (int i = 1;; i = i + 3) { try { sempahoreOne.acquire(); System.out.println(i); sempahoreTwo.release(); } catch (InterruptedException e) { e.printStackTrace(); } } } } class PrintTwoNumber implements Runnable { Semaphore sempahoreTwo; Semaphore sempahoreThree; public PrintTwoNumber(Semaphore sempahoreTwo, Semaphore sempahoreThree) { this.sempahoreTwo = sempahoreTwo; this.sempahoreThree = sempahoreThree; } @Override public void run() { for (int i = 2;; i = i + 3) { try { sempahoreTwo.acquire(); Thread.sleep(1000); System.out.println(i); sempahoreThree.release(); } catch (InterruptedException e) { e.printStackTrace(); } } } } class PrintThreeNumber implements Runnable { Semaphore sempahoreThree; Semaphore sempahoreOne; public PrintThreeNumber(Semaphore sempahoreThree, Semaphore sempahoreOne) { this.sempahoreThree = sempahoreThree; this.sempahoreOne = sempahoreOne; } @Override public void run() { for (int i = 3;; i = i + 3) { try { sempahoreThree.acquire(); Thread.sleep(1000); System.out.println(i); sempahoreOne.release(); } catch (InterruptedException e) { e.printStackTrace(); } } } }Run the program as a Java Application -