Follow these steps to implement the example:
- Create a class named Task and specify that it implements the Runnable interface:
public class Task implements Runnable {
- Declare a private Lock attribute named lock:
private final Lock lock;
- Implement the constructor of the class to initialize its attribute:
public Task (Lock lock) {
this.lock=lock;
}
- Implement the run() method:
@Override
public void run() {
System.out.printf("%s: Starting ",
Thread.currentThread().getName());
- Acquire the lock using the lock() method:
lock.lock();
- Call the criticalSection() method:
try {
criticalSection();
- Read a line from the console:
System.out.printf("%s: Press a key to continue: ",
Thread.currentThread().getName());
InputStreamReader converter = new InputStreamReader
(System.in);
BufferedReader in = new BufferedReader(converter);
String line=in.readLine();
} catch (IOException e) {
e.printStackTrace();
- Free the lock using the unlock() method in the finally section:
} finally {
lock.unlock();
}
}
- Implement the criticalSection() method. Wait for a random period of time:
private void criticalSection() {
Random random=new Random();
int wait=random.nextInt(10);
System.out.printf("%s: Wait for %d seconds ",
Thread.currentThread().getName(),wait);
try {
TimeUnit.SECONDS.sleep(wait);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
- Implement the main class of the application by creating a class named Main and adding the main() method to it:
public class Main {
public static void main(String[] args) {
- Create a new ReentrantLock object named lock. Create 10 Task objects and 10 threads to execute them:
ReentrantLock lock=new ReentrantLock();
for (int i=0; i<10; i++) {
Task task=new Task(lock);
Thread thread=new Thread(task);
thread.start();
}