O'Reilly logo

Java 9 Concurrency Cookbook - Second Edition by Javier Fernández González

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

Follow these steps to implement the example:

  1. Create a class named Task and specify that it implements the Runnable interface:
        public class Task implements Runnable {
  1. Declare a private Lock attribute named lock:
        private final Lock lock;
  1. Implement the constructor of the class to initialize its attribute:
        public Task (Lock lock) {           this.lock=lock;         }
  1. Implement the run() method:
        @Override         public void run() {           System.out.printf("%s: Starting\n",                            Thread.currentThread().getName());
  1. Acquire the lock using the lock() method:
        lock.lock();
  1. Call the criticalSection() method:
        try {           criticalSection();
  1. Read a line from the console:
          System.out.printf("%s: Press a key to continue: \n", Thread.currentThread().getName()); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required