How to do it...

Perform the following steps to implement the example:

  1. Create a class named Task that implements the Runnable interface:
        public class Task implements Runnable { 
  1. Declare a private Semaphore attribute named semaphore:
        private final Semaphore semaphore; 
  1. Implement the constructor of the class to initialize its attribute:
        public Task(Semaphore semaphore){           this.semaphore=semaphore;         } 
  1. Implement the run() method. First, acquire permit for the semaphore attribute writing a message in the console to indicate that circumstance:
        @Override         public void run() {           try {             semaphore.acquire();             System.out.printf("%s: Get the semaphore.\n",                              Thread.currentThread().getName()); 
  1. Then, put the thread to sleep for two seconds using ...

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.