How to do it...

Follow these steps to implement the example:

  1. Create a class named Task that extends the Runnable interface:
        public class Task implements Runnable {
  1. Declare a private ReentrantLock attribute named lock:
        private ReentrantLock lock;
  1. Implement a constructor of the class:
        public Task(ReentrantLock lock) {           this.lock=lock;         }
  1. Implement the run() method. Get control of the lock, put the thread to sleep for 2 seconds, and free the lock:
        @Override         public void run() {           lock.lock();           try {             TimeUnit.SECONDS.sleep(1);             lock.unlock();           } catch (InterruptedException e) {             e.printStackTrace();           }         }
  1. Create the main class of the example by creating a class named Main with a main() method:
        public class Main {  public static ...

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.