gpt4 book ai didi

java ArrayBlockingQueue同时put和take会导致死锁吗?

转载 作者:行者123 更新时间:2023-12-02 05:26:31 29 4
gpt4 key购买 nike

ArrayBlockingQueue 的 take 和 put 函数的作用如下:

`final Object[] items = new Object[100];
int putptr, takeptr, count;

public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}

public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}
`

我的问题是假设现在队列中没有元素,我调用 take()。那么调用线程将通过 notEmpty.await() 等待,同时该线程持有锁的监视器。如果我从另一个线程调用 put() ,该线程假设将新元素添加到队列中,则 put() 函数将在 lock.lock() 行等待,直到 take() 调用unlock()。我对么?如果我是对的,就会出现僵局。

最佳答案

不,Condition#await() 的 javadoc州

The lock associated with this Condition is atomically released and the current thread becomes disabled for thread scheduling purposes and lies dormant until one of four things happens: [...]

因此Lock对象被释放并且可以被另一个线程获取。

关于java ArrayBlockingQueue同时put和take会导致死锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25964496/

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