Semaphore in Java

Semaphore is an important topic and used under Multi-threading in Java. Semaphore is mainly maintains a set of permits by acquire() and release(). Each acquire() will holds the block if permits are available and it performs the Thread operation and release() the block once it completed the operation. However, no actual permit objects are used; the Semaphore just keeps a count of the number available blocks and acts accordingly. We can Semaphore is as same as wait and notify where often used to restrict the number of threads than can access some (physical or logical) resource.Below are the list of methods and constructors present in Semaphore class.

Constructors:

There are 2 types of Constructors in Semaphore class

Semaphore(int permits)

Semaphore(int permits, boolean fair)

Methods:

void acquire()

void acquire(int permits)

void acquireUninterruptibly()

void acquireUninterruptibly(int permits)

int availablePermits()

int drainPermits()

protected Collection<Thread> getQueuedThreads()

int getQueueLength()

boolean hasQueuedThreads()

boolean isFair()

protected void reducePermits(int reduction)

void release()

void release(int permits)

String toString()

boolean tryAcquire()

boolean tryAcquire(int permits)

boolean tryAcquire(int permits, long timeout, TimeUnit unit)

boolean tryAcquire(long timeout, TimeUnit unit)

Now we will simple example for using Semaphore in multi-threading. There are 2 different threads which prints even number by 1 thread and odd numbers by other thread. Numbers should be printed in sequential order like 1,2,3,4,5... etc., using Semaphore class.