Perform the following steps to implement the example:
- Create a class named Task that implements the Runnable interface:
public class Task implements Runnable {
- Declare a private Semaphore attribute named semaphore:
private final Semaphore semaphore;
- Implement the constructor of the class to initialize its attribute:
public Task(Semaphore semaphore){ this.semaphore=semaphore; }
- 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());
- Then, put the thread to sleep for two seconds using ...