Digital Marketing

Java Semaphore example

import java.util.concurrent.Semaphore;
class Foo {

Semaphore semaphore2 = new Semaphore(0);
Semaphore semaphore3 = new Semaphore(0);

public Foo() {


public void first(Runnable printFirst) throws InterruptedException {
// outputs "first". Do not change or remove this line.;

public void second(Runnable printSecond) throws InterruptedException {
// outputs "second". Do not change or remove this line.;


public void third(Runnable printThird) throws InterruptedException {
// outputs "third". Do not change or remove this line.;

Semaphore is a class in java.util.concurrent package introduced in JDK 5. Semaphore basically maintains a set of permits, so there are two methods which are mainly used for semaphore.
  • acquire
  • release
acquire() method is used to get a permit and if no. of permits reaches max allowed permits then thread has to wait to get permit which will be released by some other thread by calling release() method.
Semaphores are generally used to restrict the number of threads to access resources.


Popular posts from this blog

MySQL Sandbox with the Sakila sample database