A semaphore maintains a fixed number of threads in executions if exceeds lock can be acquired for that semaphore thread.
Below method will get the lock of semaphore within semaphore.availablePermits()
1 |
semaphore.acquire() |
If there are more that fixed threads, it will wait to acquire/get the semaphore lock until it has semaphore.availablepermits() greater than ‘0’.
A semaphore initialised to one, has only one permit available is a mutual exclusion lock, which we can say as “mutex“.
This is more commonly known as a binary semaphore, as it has 2 states, zero permit and one permit, and lock can be released from other threads.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package my.test.learning; import java.util.concurrent.Semaphore; public class SemaphoreExample { public static void main(String[] args) { Semaphore semaphore = new Semaphore(4); Thread thread1 = new Thread(new SampleThread(semaphore)); Thread thread2 = new Thread(new SampleThread(semaphore)); Thread thread3 = new Thread(new SampleThread(semaphore)); Thread thread4 = new Thread(new SampleThread(semaphore)); Thread thread5 = new Thread(new SampleThread(semaphore)); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); } } class SampleThread implements Runnable { Semaphore semaphore; public SampleThread(Semaphore semaphore) { this.semaphore = semaphore; } @Override public void run() { String name = Thread.currentThread().getName(); try { System.out.println(name + " getting the semaphore lock"); semaphore.acquire(); System.out.println(" Received the available semaphore permit " + name); Thread.sleep(2000); System.out.println("Available Semaphore permits : " + semaphore.availablePermits()); semaphore.release(); System.out.println(name + " - release the Semaphore lock"); } catch (InterruptedException e) { e.printStackTrace(); } } } |
Result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Thread-0 getting the semaphore lock Received the available semaphore permit Thread-0 Thread-1 getting the semaphore lock Received the available semaphore permit Thread-1 Thread-4 getting the semaphore lock Received the available semaphore permit Thread-4 Thread-3 getting the semaphore lock Received the available semaphore permit Thread-3 Thread-2 getting the semaphore lock Available Semaphore permits : 0 Available Semaphore permits : 0 Thread-0 - release the Semaphore lock Thread-1 - release the Semaphore lock Received the available semaphore permit Thread-2 Available Semaphore permits : 1 Thread-3 - release the Semaphore lock Available Semaphore permits : 1 Thread-4 - release the Semaphore lock Available Semaphore permits : 3 Thread-2 - release the Semaphore lock |