How it works...

The key to this example is the printJob() method of the PrintQueue class. This method shows three steps you must follow when you use a semaphore to implement a critical section and protect access to a shared resource:

  1. First, you acquire the semaphore with the acquire() method.
  2. Then, you do the necessary operations with the shared resource.
  3. Finally, release the semaphore with the release() method.

Another important point in this example is the constructor of the PrintQueue class and the initialization of the Semaphore object. You pass the value 3 as the parameter of this constructor, so you are creating a semaphore that will protect three resources. The first three threads that call the acquire() method will get access to ...

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.