ReentrantLock reentrant lock

A, Lock Interface:

  After Java SE 5, and added a contracting Lock interfaces and associated implementation class to implement the lock function.

 Lock Lock realize the difference between the interface and the synchronized keyword:

Acquiring and releasing locks, sychronized implicit acquiring and releasing locks (1) Lock the interface to be displayed. Precisely because of this, so that the interface has a Lock lock acquisition and release of operability, interruptible lock acquisition timeout acquire synchronization feature a variety of synchronized keyword lock not available.

For example: a scene, to acquire the lock A, B and then acquire the lock, when B is obtained, while the release of A, while acquiring the lock C. And so on. This scenario synchronized bad realized.

(2) non-blocking attempt to acquire the lock: the current thread tries to acquire the lock if no other thread this time to acquire the lock is successfully acquired and holds the lock.

(3) can be interrupted acquisition: Get to lock the thread is able to respond to the interrupt, when the acquired lock the thread is interrupted, interrupt exception will be thrown, while the lock is released.

(4) to acquire the lock timeout: to acquire a lock before the specified deadline, if the deadline is still unable to acquire the lock is returned.

Lock lock = new ReentrantLock();
lock.lock;
try{
}finally{
    lock.unlock();  
}

2, Lock Common Interface API

Two, ReentrantLock reentrant lock

1, ReentrantLock: support the re-entry of the lock, namely: the ability to support a thread duplication of resources locked. In addition, the lock also supports equity and non-equity of choice when acquiring a lock, a non-default fair locks.

  ReentrantLock when calling lock () method, has been acquired to lock the thread can call the lock again () method to get the lock, without being blocked.

 

supplement:

Fairness lock: fairness is for the purposes of acquiring the lock, if a lock is fair, then lock acquisition order should be in line with the request of an absolute chronological order, it is FIFO.

  Unfair locks may make thread "hunger", and fair locks require a lot of thread switch

 

2. Implementation Mechanism:

Guess you like

Origin www.cnblogs.com/guoyu1/p/12179423.html