java多线程|| Lock,ReentrantLock,lock(),tryLock()最简明解释

本文详细介绍了Java中的Lock接口及其实现类ReentrantLock的各种方法,包括lock(), lockInterruptibly(), tryLock()及其带参数版本。通过对比这些方法的行为特征,帮助读者理解不同场景下锁的应用策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,Lock是一个接口,ReentrantLock是Lock的常用实现类。

其次,lock.lock()是一个阻塞方法,而lock.tryLock()不是,它是一个有返回值的方法。

除了lock(),trylock()方法,还有另外两个常见方法一起比较一下:

- void lock();

If the lock is not available then the current thread becomes disabled
for thread scheduling purposes and lies dormant until the lock has
been acquired.

在等待获取锁的过程中休眠并禁止一切线程调度

- void lockInterruptibly() throws InterruptedException;

If the lock is not available then the current thread becomes disabled
for thread scheduling purposes and lies dormant until one of two
things happens: The lock is acquired by the current thread; or Some
other thread interrupts the current thread, and interruption of lock
acquisition is supported.

在等待获取锁的过程中可被中断

- boolean tryLock();

Acquires the lock if it is available and returns immediately with the
value true. If the lock is not available then this method will return
immediately with the value false.

获取到锁并返回true;获取不到并返回false

- boolean tryLock(long time, TimeUnit unit) throws InterruptedException;

If the lock is available this method returns immediately with the
value true. If the lock is not available 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, and
interruption of lock acquisition is supported; or The specified
waiting time elapses.

在指定时间内等待获取锁;过程中可被中断

最后举一个例子:

假设线程A和线程B使用同一个锁LOCK,此时线程A首先获取到锁LOCK.lock(),并且始终持有不释放。如果此时B要去获取锁,有四种方式:

  1. LOCK.lock():
    此方式会始终处于等待中,即使调用B.interrupt()也不能中断,除非线程A调用LOCK.unlock()释放锁。
  2. LOCK.lockInterruptibly():
    此方式会等待,但当调用B.interrupt()会被中断等待,并抛出InterruptedException异常,否则会与lock()一样始终处于等待中,直到线程A释放锁。
  3. LOCK.tryLock(): 该处不会等待,获取不到锁并直接返回false,去执行下面的逻辑。
  4. LOCK.tryLock(10,
    TimeUnit.SECONDS):该处会在10秒时间内处于等待中,但当调用B.interrupt()会被中断等待,并抛出InterruptedException。10秒时间内如果线程A释放锁,会获取到锁并返回true,否则10秒过后会获取不到锁并返回false,去执行下面的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值