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 ",
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: 
",
Thread.currentThread().getName());
InputStreamReader converter = new InputStreamReader
(System.in);
BufferedReader in = new BufferedReader(converter);
String line=in.readLine();
} catch (IOException e) {
e.printStackTrace();
  1. Free the lock using the unlock() method in the finally section:
          } finally {          
lock.unlock();
}
}
  1. 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();
}
}
  1. 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) {
  1. 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();
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.20.90