我有多个资源,每个资源都由它自己的信号量控制。我想获得这些资源中的任何一个,并持有它的信号量。这类似于acquire上的OR操作:“从semaphore1或semaphore2或...或semaphoreN获取M许可。”需要说明的是,所有的M许可证都必须从一个信号量中获取。
我想要一个如下所示的方法acquire:
Semaphore acquiredSemaphore = acquire(4, semaphore1, semaphore2, semaphore3);它应该等待(或者立即返回),直到它从任何信号量获得许可,并且它应该返回信号量(这样我可以稍后释放许可给它)。我对使用方法、类或设计模式的任何组合都持开放态度。
发布于 2019-09-10 14:20:46
不过,并没有对其进行测试:
Semaphore acquire(int permits, Semaphore ... semaphores) throws InterruptedException {
Semaphore candidate = null;
while (true) { // polling loop
for (Semaphore semaphore: semaphores) {
// attempt to aquire from next Semaphore in the list
if (semaphore.tryAcquire(permits) {
return semaphore;
}
// choose the candidate semaphore with maximum available permits
if (candidate == null || candidate.availablePermits < semaphore.availablePermits) {
candidate = semaphore;
}
}
// now we have to wait some time
// instead of plain sleeping, we wait on the most filled semaphore
if (candidate.tryAcquire(permits, 10, TimeUnit.MILLISECONDS) {
return semaphore;
}
}
}https://stackoverflow.com/questions/57835442
复制相似问题