假设我有以下代码:Java的锁定条件
private final ReentrantLock resourcesLock = new ReentrantLock(true);
private Condition resourcePresentCondition= resourcesLock.newCondition();
public void requestRes() throws InterruptedException {
resourcesLock.lock();
try {
if(resources.isEmpty()) {
if(!resourcePresentCondition.await(Config.STARVE_TIME_SECONDS, TimeUnit.SECONDS)) {
if(resources.isEmpty()) {
return;
}
}
}
//No resources left if other threads gather them first
Resource resource = resources.removeFirst();
} finally {
resourcesLock.unlock();
}
}
现在,多线程进入requestRes()方法,如果没有资源都存在,他们都等待条件。另一种方法生成资源并调用resourcePresentCondition.signalAll()
。在此之后,如果时间没有用完(或者如果时间已经耗尽,并且存在资源 - 只是为了避免全部同时发生的情况),则会消耗资源。
问题是,有时资源被清空,并且获取resourcePresentCondition信号的线程会抛出异常,因为资源列表为空(.removeFirst()异常)。
什么是最好的解决方案,以避免这种情况,并使线程恢复等待(不重新开始)resourcePresentCondition?
我想看看[同步](https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html) – Nico
添加另一测试'resources.isEmpty()'之前'removeFirst'。 – Dimitri
@Nico你可能想看看[高级并发对象](https://docs.oracle.com/javase/tutorial/essential/concurrency/highlevel.html) – Kayaman