Tuesday, 27 March 2018

Please demonstrate Lock Interface using Example?


package com.test.yuvagen.basic;

import java.util.concurrent.locks.*;
/* Write a Java program that Demonstrate Lock Interface  
 * */
public class LockThreadDemo {

          private final Lock queueLock = new ReentrantLock();

          public void print() {

                   queueLock.lock();

                   try {
                             Long duration = (long) (Math.random() * 10000);
                             System.out.println(Thread.currentThread().getName() + "\ttime taken" + (duration / 1000) + "sec");
                             Thread.sleep(duration);
                   } catch (Exception e) {
                             e.printStackTrace();
                   } finally {
                             queueLock.unlock();
                   }
          }

          public static void main(String args[]) {
                   LockThreadDemo lockDemo = new LockThreadDemo();

                   ThreadLock tl1 = new ThreadLock("Thread-1", lockDemo);
                   ThreadLock tl2 = new ThreadLock("Thread-2", lockDemo);
                   ThreadLock tl3 = new ThreadLock("Thread-3", lockDemo);

                   tl1.start();
                   tl2.start();
                   tl3.start();
          }
}

class ThreadLock extends Thread {
          LockThreadDemo lockDemo;

          ThreadLock(String name, LockThreadDemo lockDemo) {
                   super(name);
                   this.lockDemo = lockDemo;
          }

          @Override
          public void run() {
                   lockDemo.print();
          }
}

Output:
Thread-1   time taken3sec
Thread-2   time taken5sec
Thread-3   time taken6sec


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...