java.util.concurrent.locks.ReentrantLock.tryLock()

2 篇文章 0 订阅
1 篇文章 0 订阅

只有在锁没有被其他线程持有的时候才获取锁


在锁没有被其他线程持有的时候获取锁并返回true值, 将锁计数器置为1. 即使已将此锁设置为使用公平排序策略,如果该锁可用,则调用tryLock()将立即获取该锁,而不管其他线程当前是否正在等待该锁. 这种”恶霸式(barging)”的行为在某些情况下会很有用,即使它打破了公平. 如果你想保持这个锁的公正性, 则使用tryLock(0, TimeUnit.SECONDS)(这个方法同事也侦测中断).


如果当前线程已经持有该锁,那么锁计数器自增1并且该方法返回true


如果该锁被其他线程持有,那么直接返回false


Specified by: tryLock() in Lock


Returns:
当该锁未被持有或已被当前线程持有时返回true,否则返回fasle


Acquires the lock only if it is not held by another thread at the time of invocation.


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. Even when this lock has been set to use a fair ordering policy, a call to tryLock() will immediately acquire the lock if it is available, whether or not other threads are currently waiting for the lock. This “barging” behavior can be useful in certain circumstances, even though it breaks fairness. If you want to honor the fairness setting for this lock, then use tryLock(0, TimeUnit.SECONDS) which is almost equivalent (it also detects interruption).


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 this method will return immediately with the value false.


Specified by: tryLock() in Lock


Returns:
true if the lock was free and was acquired by the current thread, or the lock was already held by the current thread; and false otherwise

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值