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 {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
semaphore2.release();
}

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

}

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


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.

Comments

Popular posts from this blog

Check MySQL query history from command line

Installing chocolatey on Windows