How it works...

In the following screenshot, you can see a part of the output of one execution of this example:

The key to the example is in the printJob() method of the PrintQueue class. When we want to implement a critical section using locks and guarantee that only one execution thread will run a block of code, we have to create a ReentrantLock object. At the beginning of the critical section, we have to get control of the lock using the lock() method. When thread (A) calls this method, if no other thread has control of the lock, it gives thread (A) control of the lock and returns immediately to allow the thread to execute the critical ...

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.