How to do it...

Follow these steps to implement the example:

  1. Create a class named Task1 and specify that it implements the Runnable interface:
        public class Task1 implements Runnable {
  1. Declare two private Lock attributes, named lock1 and lock2:
        private Lock lock1, lock2;
  1. Implement the constructor of the class to initialize its attributes:
        public Task1 (Lock lock1, Lock lock2) {           this.lock1=lock1;           this.lock2=lock2;         }
  1. Implement the run() method. First, get control of the lock1 object using the lock() method and write aa message in the console indicating that you have got it:
        @Override         public void run() {           lock1.lock();           System.out.printf("Task 1: Lock 1 locked\n");
  1. Then, get control of lock2 using the lock() method and write ...

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.