ReentrantLock

  • public class ReentrantLock
    extends Object
    implements Lock, Serializable
    A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

    A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock. This can be checked using methods isHeldByCurrentThread(), and getHoldCount().

    The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting. 


             一个可重入的互斥锁除了在扩展性上与同步方法和声明的隐式监控锁不同外,在基本行为和语义上都相同。一个拥有可重入锁的线程最后成功锁定,但尚未解锁它。当这个锁并没有被其他线程拥有时,一个线程调用锁,将成功的返回请求的这个锁。如果当前线程已经拥有该锁了,该方法会立刻返回。这可以通过isHeldByCurrentThread()和getHoldCount()两个方法检查。
        
        该类的构造器接收一个可选的清晰的参数,当设置true时,在有争议的情况下,锁偏爱给与等待最长时间的线程。否则该锁不能保证任何特定的访问顺序,许多线程访问公平 锁的程序可能显示较低的整体吞吐量(即,比那些使用默认设置慢),但是对于及时获锁和保证避免饥饿有较小的差异。然而,锁的公平并不能保证线程调度的公平性。这样,使用一个公平锁的许多线程可以在继承中多次获得它,而其他活跃的线程由于当前没有持有锁就无法运行。需要注意的是不定时的tryLock方法并不会遵守公平性的设置。在有锁的情况下,即使其他线程正在等待,它也会成功。

使用可重入锁的格式
class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值