I need clarification regarding an issue related to multithreading. I have threads which acquires a semaphore, and after a while releases it. As soon as it is done releasing first semaphore, it acquires second one and after while releases it. Both semaphore protects different code in thread’s run() method. Something like below:
public void run() {
System.out.println("Step 1");
semaphoreA.acquire();
// Run for a while
semaphoreA.release();
// Run for a while
semaphoreB.acquire();
System.out.println("Step 2");
// Run for a while
semaphoreB.release();
}
So, when there is no permit for semaphoreB, thread waits. However, when the permit made available, shouldn’t I see ‘Step 2’ on console ? Or that is how thread and semaphore works ?
I want to understand what happens if a thread was just notified about an available semaphore permit. Would that thread start from the beginning ? or From the point where it was left of ?
Assuming that you instantiated semaphoreA and SemaphoreB with new Semaphore(1, true) at best you will see:
Step 1
Step 2
If some other thread acquires the semaphore, until it is released, this thread just waits where it is. In other words, you will never Step 1 once, but never twice. You may or not see Step 2 depending if any of the semaphores is released.