ReentrantLock
2016-04-04 09:33
337 查看
public class ReentrantLock extends Object implements Lock, Serializable
A reentrant mutual exclusion
Lockwith the same basic behavior and semantics as the implicit monitor lock accessed using
synchronizedmethods and statements, but with extended capabilities.
A
ReentrantLockis owned by the thread last successfully locking, but not yet unlocking it. A thread invoking
lockwill 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
tryLockmethod 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() } } }
相关文章推荐
- 三分钟掌握 JUnit3.0
- A working DHCPCD Hook system
- 非侵入式
- linux下创建库函数
- android中horizontal和vertical的区别
- MySQL 学习笔记(2)2016-04-04
- View.inflate和LayoutInflater的inflate方法区别
- 包装类怎么参与运算的
- 内购
- [转]Flex 布局教程:语法篇
- 2016中山市邀请赛
- LayoutTransition(布局容器动画)
- swift可选类型
- CodeForces - 659B Qualifying Contest (模拟)水
- C# 读取EXCEL文件的三种经典方法
- 8种基本数据类型和运算(隐式转换和强制转换)
- MySQL 学习笔记(1)2016-04-02
- python 实现类似tweproxy 和codes的功能的redis代理功能
- PHP微信表白墙重构(一)概述
- jquery给h1和span赋值