Question 15
Back to Exercise
What is the output of the following Java program?
import java.util.concurrent.Semaphore;
public class Main {
public static void main(String[] args) throws InterruptedException {
Semaphore s = new Semaphore(3);
s.acquire();
s.acquire(2);
boolean got = s.tryAcquire(); // no permits left: returns false immediately
int avail = s.availablePermits();
s.release(2);
System.out.println(got + " " + avail + " " + s.availablePermits() + " " + s.tryAcquire());
}
}
- A false 0 2 true Correct
- B true 0 2 true
- C false 1 3 true
- D false 0 2 false
Correct Answer: Option A
Three permits are taken, so tryAcquire fails; releasing two makes two available, and the final tryAcquire succeeds.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!