- 所有已实现的接口:
-
Serializable
,Lock
synchronized
方法和语句访问的隐式监视器锁相同的基本行为和语义的可重入互斥Lock
,但具有扩展功能。
ReentrantLock
由最后成功锁定但尚未解锁的线程“拥有”。当锁未被另一个线程拥有时,调用lock
的线程将返回,成功获取锁。如果当前线程已经拥有锁,则该方法将立即返回。可以使用isHeldByCurrentThread()
和getHoldCount()
方法来检查这一点。
此类的构造函数接受一个可选的“公平性”参数。当设置为true
时,在争用情况下,锁倾向于授予访问权给等待时间最长的线程。否则,此锁不保证任何特定的访问顺序。使用被许多线程访问的公平锁的程序可能显示较低的总体吞吐量(即,速度较慢;通常慢得多),但在获取锁的时间和保证不会饥饿方面具有较小的差异。但请注意,锁的公平性并不保证线程调度的公平性。因此,使用公平锁的众多线程之一可能连续多次获取它,而其他活动线程没有进展并且当前未持有锁。还请注意,未定时的tryLock()
方法不遵守公平性设置。即使其他线程正在等待,如果锁可用,它也会成功。
建议实践是始终立即在调用lock
后跟一个try
块,通常在before/after构造中,例如:
class X {
private final ReentrantLock lock = new ReentrantLock();
// ...
public void m() {
lock.lock(); // 阻塞直到条件成立
try {
// ... 方法体
} finally {
lock.unlock();
}
}
}
除了实现Lock
接口外,此类还定义了一些用于检查锁状态的public
和protected
方法。其中一些方法仅对仪器化和监视有用。
此类的序列化行为与内置锁相同:反序列化的锁处于未锁定状态,而不管其在序列化时的状态如何。
此锁支持同一线程的最大2147483647个递归锁。尝试超过此限制将导致从锁定方法中抛出Error
。
- 自:
- 1.5
- 参见:
-
Constructor Summary
ConstructorDescription创建ReentrantLock
的实例。ReentrantLock
(boolean fair) 使用给定的公平性策略创建ReentrantLock
的实例。 -
Method Summary
Modifier and TypeMethodDescriptionint
查询当前线程对此锁的持有次数。protected Thread
getOwner()
返回当前拥有此锁的线程,如果未拥有则返回null
。protected Collection
<Thread> 返回包含可能正在等待获取此锁的线程的集合。final int
返回等待获取此锁的线程数的估计值。protected Collection
<Thread> getWaitingThreads
(Condition condition) 返回包含可能正在等待与此锁关联的给定条件的线程的集合。int
getWaitQueueLength
(Condition condition) 返回等待与此锁关联的给定条件的线程数的估计值。final boolean
hasQueuedThread
(Thread thread) 查询给定线程是否正在等待获取此锁。final boolean
查询是否有任何线程正在等待获取此锁。boolean
hasWaiters
(Condition condition) 查询是否有任何线程正在等待与此锁关联的给定条件。final boolean
isFair()
如果此锁已设置为公平性为true,则返回true
。boolean
查询当前线程是否持有此锁。boolean
isLocked()
查询是否有任何线程持有此锁。void
lock()
获取锁。void
获取锁,除非当前线程被中断。toString()
返回标识此锁及其锁状态的字符串。boolean
tryLock()
仅当调用时,如果此锁未被另一个线程持有,则获取锁。boolean
仅当在给定等待时间内未被另一个线程持有且当前线程未被中断时,获取锁。void
unlock()
尝试释放此锁。
-
Constructor Details
-
ReentrantLock
public ReentrantLock()创建ReentrantLock
的实例。这等效于使用ReentrantLock(false)
。 -
ReentrantLock
public ReentrantLock(boolean fair) 使用给定的公平性策略创建ReentrantLock
的实例。- 参数:
-
fair
- 如果此锁应使用公平排序策略,则为true
-
-
Method Details
-
lock
public void lock()获取锁。如果此锁未被另一个线程持有,则获取锁并立即返回,将锁持有计数设置为一。
如果当前线程已经持有此锁,则持有计数将增加一,并且方法将立即返回。
如果锁被另一个线程持有,则当前线程将为了线程调度目的而被禁用,并处于休眠状态,直到获取锁为止,此时锁持有计数设置为一。
-
lockInterruptibly
除非当前线程被中断,否则获取锁。如果此锁未被另一个线程持有,则获取锁并立即返回,将锁持有计数设置为一。
如果当前线程已经持有此锁,则持有计数将增加一,并且方法将立即返回。
如果锁被另一个线程持有,则当前线程将为了线程调度目的而被禁用,并处于休眠状态,直到发生以下两种情况之一:
- 当前线程获取锁;或
- 其他线程中断当前线程。
如果当前线程获取锁,则锁持有计数设置为一。
如果当前线程:
- 在进入此方法时设置了中断状态;或
- 在获取锁时被中断,
InterruptedException
,并清除当前线程的中断状态。在此实现中,由于此方法是显式中断点,因此优先响应中断而不是正常或可重入地获取锁。
- 指定者:
-
lockInterruptibly
在接口Lock
中 - 抛出:
-
InterruptedException
- 如果当前线程被中断
-
tryLock
public boolean tryLock()仅当调用时,如果此锁未被另一个线程持有,则获取锁。如果此锁未被另一个线程持有,则获取锁并立即返回,将锁持有计数设置为一。即使此锁已设置为使用公平排序策略,调用
tryLock()
将立即获取锁(如果可用),无论当前是否有其他线程正在等待锁。这种“闯入”行为在某些情况下可能很有用,尽管它破坏了公平性。如果要遵守此锁的公平性设置,则使用tryLock(0, TimeUnit.SECONDS)
,几乎等效(它还会检测中断)。如果当前线程已经持有此锁,则持有计数将增加一,并且方法将返回
true
。如果锁被另一个线程持有,则此方法将立即返回
false
。 -
tryLock
Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted.Acquires the lock if it is not held by another thread and returns immediately with the value
true
, setting the lock hold count to one. If this lock has been set to use a fair ordering policy then an available lock will not be acquired if any other threads are waiting for the lock. This is in contrast to thetryLock()
method. If you want a timedtryLock
that does permit barging on a fair lock then combine the timed and un-timed forms together:if (lock.tryLock() || lock.tryLock(timeout, unit)) { ... }
If the current thread already holds this lock then the hold count is incremented by one and the method returns
true
.If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:
- The lock is acquired by the current thread; or
- Some other thread interrupts the current thread; or
- The specified waiting time elapses
If the lock is acquired then the value
true
is returned and the lock hold count is set to one.If the current thread:
- has its interrupted status set on entry to this method; or
- is interrupted while acquiring the lock,
InterruptedException
is thrown and the current thread's interrupted status is cleared.If the specified waiting time elapses then the value
false
is returned. If the time is less than or equal to zero, the method will not wait at all.In this implementation, as this method is an explicit interruption point, preference is given to responding to the interrupt over normal or reentrant acquisition of the lock, and over reporting the elapse of the waiting time.
- Specified by:
-
tryLock
in interfaceLock
- Parameters:
-
timeout
- the time to wait for the lock -
unit
- the time unit of the timeout argument - Returns:
-
true
if the lock was free and was acquired by the current thread, or the lock was already held by the current thread; andfalse
if the waiting time elapsed before the lock could be acquired - Throws:
-
InterruptedException
- if the current thread is interrupted -
NullPointerException
- if the time unit is null
-
unlock
public void unlock()Attempts to release this lock.If the current thread is the holder of this lock then the hold count is decremented. If the hold count is now zero then the lock is released. If the current thread is not the holder of this lock then
IllegalMonitorStateException
is thrown.- Specified by:
-
unlock
in interfaceLock
- Throws:
-
IllegalMonitorStateException
- if the current thread does not hold this lock
-
newCondition
Returns aCondition
instance for use with thisLock
instance.The returned
Condition
instance supports the same usages as do theObject
monitor methods (wait
,notify
, andnotifyAll
) when used with the built-in monitor lock.- If this lock is not held when any of the
Condition
waiting or signalling methods are called, then anIllegalMonitorStateException
is thrown. - When the condition waiting methods are called the lock is released and, before they return, the lock is reacquired and the lock hold count restored to what it was when the method was called.
- If a thread is interrupted while waiting then the wait will terminate, an
InterruptedException
will be thrown, and the thread's interrupted status will be cleared. - Waiting threads are signalled in FIFO order.
- The ordering of lock reacquisition for threads returning from waiting methods is the same as for threads initially acquiring the lock, which is in the default case not specified, but for fair locks favors those threads that have been waiting the longest.
- Specified by:
-
newCondition
in interfaceLock
- Returns:
- the Condition object
- If this lock is not held when any of the
-
getHoldCount
public int getHoldCount()Queries the number of holds on this lock by the current thread.A thread has a hold on a lock for each lock action that is not matched by an unlock action.
The hold count information is typically only used for testing and debugging purposes. For example, if a certain section of code should not be entered with the lock already held then we can assert that fact:
class X { final ReentrantLock lock = new ReentrantLock(); // ... public void m() { assert lock.getHoldCount() == 0; lock.lock(); try { // ... method body } finally { lock.unlock(); } } }
- Returns:
- the number of holds on this lock by the current thread, or zero if this lock is not held by the current thread
-
isHeldByCurrentThread
public boolean isHeldByCurrentThread()Queries if this lock is held by the current thread.Analogous to the
Thread.holdsLock(Object)
method for built-in monitor locks, this method is typically used for debugging and testing. For example, a method that should only be called while a lock is held can assert that this is the case:class X { final ReentrantLock lock = new ReentrantLock(); // ... public void m() { assert lock.isHeldByCurrentThread(); // ... method body } }
It can also be used to ensure that a reentrant lock is used in a non-reentrant manner, for example:
class X { final ReentrantLock lock = new ReentrantLock(); // ... public void m() { assert !lock.isHeldByCurrentThread(); lock.lock(); try { // ... method body } finally { lock.unlock(); } } }
- Returns:
-
true
if current thread holds this lock andfalse
otherwise
-
isLocked
public boolean isLocked()Queries if this lock is held by any thread. This method is designed for use in monitoring of the system state, not for synchronization control.- Returns:
-
true
if any thread holds this lock andfalse
otherwise
-
isFair
public final boolean isFair()Returnstrue
if this lock has fairness set true.- Returns:
-
true
if this lock has fairness set true
-
getOwner
Returns the thread that currently owns this lock, ornull
if not owned. When this method is called by a thread that is not the owner, the return value reflects a best-effort approximation of current lock status. For example, the owner may be momentarilynull
even if there are threads trying to acquire the lock but have not yet done so. This method is designed to facilitate construction of subclasses that provide more extensive lock monitoring facilities.- Returns:
-
the owner, or
null
if not owned
-
hasQueuedThreads
public final boolean hasQueuedThreads()Queries whether any threads are waiting to acquire this lock. Note that because cancellations may occur at any time, atrue
return does not guarantee that any other thread will ever acquire this lock. This method is designed primarily for use in monitoring of the system state.- Returns:
-
true
if there may be other threads waiting to acquire the lock
-
hasQueuedThread
Queries whether the given thread is waiting to acquire this lock. Note that because cancellations may occur at any time, atrue
return does not guarantee that this thread will ever acquire this lock. This method is designed primarily for use in monitoring of the system state.- Parameters:
-
thread
- the thread - Returns:
-
true
if the given thread is queued waiting for this lock - Throws:
-
NullPointerException
- if the thread is null
-
getQueueLength
public final int getQueueLength()Returns an estimate of the number of threads waiting to acquire this lock. The value is only an estimate because the number of threads may change dynamically while this method traverses internal data structures. This method is designed for use in monitoring system state, not for synchronization control.- Returns:
- the estimated number of threads waiting for this lock
-
getQueuedThreads
Returns a collection containing threads that may be waiting to acquire this lock. Because the actual set of threads may change dynamically while constructing this result, the returned collection is only a best-effort estimate. The elements of the returned collection are in no particular order. This method is designed to facilitate construction of subclasses that provide more extensive monitoring facilities.- Returns:
- the collection of threads
-
hasWaiters
查询与此锁关联的给定条件上是否有任何线程正在等待。请注意,由于超时和中断可能随时发生,因此返回true
并不保证将来的signal
会唤醒任何线程。此方法主要设计用于监视系统状态。- 参数:
-
condition
- 条件 - 返回:
-
如果有任何等待的线程,则返回
true
- 抛出:
-
IllegalMonitorStateException
- 如果未持有此锁 -
IllegalArgumentException
- 如果给定条件与此锁不关联 -
NullPointerException
- 如果条件为null
-
getWaitQueueLength
返回与此锁关联的给定条件上正在等待的线程数的估计值。请注意,由于超时和中断可能随时发生,因此该估计值仅作为实际等待线程数量的上限。此方法设计用于监视系统状态,而不是用于同步控制。- 参数:
-
condition
- 条件 - 返回:
- 估计的等待线程数
- 抛出:
-
IllegalMonitorStateException
- 如果未持有此锁 -
IllegalArgumentException
- 如果给定条件与此锁不关联 -
NullPointerException
- 如果条件为null
-
getWaitingThreads
返回包含可能正在等待与此锁关联的给定条件的线程的集合。由于实际线程集可能在构造此结果时动态更改,因此返回的集合仅是最佳估计。返回的集合中的元素没有特定顺序。此方法旨在促进提供更广泛的条件监视功能的子类的构建。- 参数:
-
condition
- 条件 - 返回:
- 线程的集合
- 抛出:
-
IllegalMonitorStateException
- 如果未持有此锁 -
IllegalArgumentException
- 如果给定条件与此锁不关联 -
NullPointerException
- 如果条件为null
-
toString
-