Tuesday 23 September 2014

ReentrantLock

ReentrantLock is the implementation of Lock interface. ReentrantLock class defines a number of public and protected methods for inspecting the state of the lock. This lock supports a maximum of 2147483647 recursive locks by the same thread. Attempts to exceed this limit result in Error throws from locking methods.

Constructors provided by this class
Constructor Description
public ReentrantLock() Creates an instance of ReentrantLock
public ReentrantLock(boolean fair) Creates an instance of ReentrantLock. This constructor accepts an optional fairness parameter. If fair set to true, under contention, locks favor granting access to the longest-waiting thread.

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.TimeUnit;
import java.lang.Object;

public class Task implements Runnable{
    
   int taskNum;
   static Lock myLock = new ReentrantLock(true);
   
   Task(int taskNum){
       this.taskNum = taskNum;
   }
    
   @Override
   public void run(){
       myLock.lock();
       try {
           System.out.println(taskNum +" Started ");
           try {
               TimeUnit.SECONDS.sleep(1);
           } catch (InterruptedException ex) {
               
           }
           System.out.println(taskNum +" Finished ");
        }
       finally {
          myLock.unlock();
       }
    }
}

public class LockEx {
    public static void main(String args[]){
        int taskNum = 1;
        
        while(taskNum < 50){
            Task task = new Task(taskNum);
            new Thread(task).start();
            taskNum++;
        }
    }
}

Sample Output
1 Started 
1 Finished 
2 Started 
2 Finished 
3 Started 
3 Finished 
4 Started 
4 Finished 
5 Started 
5 Finished 
6 Started 
6 Finished 






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment