Follow these steps to implement the example:
- Create a class named Task that extends the Runnable interface:
public class Task implements Runnable {
- Declare a private ReentrantLock attribute named lock:
private ReentrantLock lock;
- Implement a constructor of the class:
public Task(ReentrantLock lock) { this.lock=lock; }
- 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(); } }
- Create the main class of the example by creating a class named Main with a main() method:
public class Main { public static ...