gpt4 book ai didi

java - 为什么在 Java 的 ArrayBlockingQueue 实现中在 Offer(E e) 中使用 lock() 而在 put(E e) 中使用 lockInterruptically()

转载 作者:行者123 更新时间:2023-11-30 03:52:12 26 4
gpt4 key购买 nike

我对Java ArrayBlockingQueue源代码中的锁感到困惑。

put(E e)中,这里使用了lockInterruptically():

public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
insert(e);
} finally {
lock.unlock();
}
}

但是在offer(E e)中,使用了lock():

public boolean offer(E e) {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (count == items.length)
return false;
else {
insert(e);
return true;
}
} finally {
lock.unlock();
}
}

据我所知,lock()lockInterruptically() 的区别在于后者立即响应中断。

请问为什么作者在 offer(E e) 中选择 lock() 而在 put( E e) ?可以互换吗?

最佳答案

我怀疑差异是由于 offer()put() 的语义不同造成的。来自 javadoc :

offer(E e)

Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and false if this queue is full.

put(E e)

Inserts the specified element at the tail of this queue, waiting for space to become available if the queue is full.

由于 put() 需要能够等待,因此它也可以被中断。 javadoc for lockInterruptibly()状态:

If the lock is held by another thread 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.

If the current thread:

  • has its interrupted status set on entry to this method; or
  • is interrupted while acquiring the lock,

then InterruptedException is thrown and the current thread's interrupted status is cleared.

所以lockInterruptically()允许程序在获取锁之前或期间立即响应被中断的线程,而lock()则不能(要老实说,我不确定如果等待线程在等待lock()时被中断会发生什么,但似乎javadoc似乎暗示中断将被吞噬并忽略)。 p>

考虑到 offer()put() 的语义,我认为选择这些锁定方法是为了最好地匹配其包含方法的语义。

关于java - 为什么在 Java 的 ArrayBlockingQueue 实现中在 Offer(E e) 中使用 lock() 而在 put(E e) 中使用 lockInterruptically(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24154382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com