Reputation: 18639
I have one static Semaphore instance.
Semaphore semaphore = new Semaphore(1);
Now I have two Threads (Sending Thread and Receiving Thread)
Sending Thread:
public class SendingThread implements Runnable {
private Semaphore semaphore;
public SendingThread(Semaphore semaphore){
this.semaphore = semaphore;
}
@Override
public void run() {
try {
System.out.println("1");
Thread.sleep(4000);
this.semaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
and receiving Thread:
public class RecievingThread implements Runnable {
private Semaphore semaphore;
public RecievingThread(Semaphore semaphore){
this.semaphore = semaphore;
}
@Override
public void run() {
System.out.println("2");
this.semaphore.release();
System.out.println("3");
}
}
When I start this 2 threads according to my understanding Receiving Thread will wait for 4 second till
Sending Thread will notify it that Receiving Thread can continue. It means that System.out.println("3");
will be printed with 4 second delay, but when I run this code all three values are printed immediately. Why?
Am i missing something?
Upvotes: 2
Views: 4301
Reputation: 420951
A new Semaphore(1)
has 1 initial permit and thus allows for one immediate acquire
to go through. Furthermore since a release
is always allowed both threads proceeds immediately.
To force one thing to happen before the other, you can use new Semaphore(0)
. This will force the thread calling acquire
to wait for the thread executing release
.
Upvotes: 3