那么,我如何正确使用Locks或Concurrency或.wait()/.notify()来确保昂贵的工作只运行设定的次数呢?
这个
Semaphore
泰勒就是为这种事情而生的吗。它有一定数量的许可证,除非有许可证,否则线程将阻塞。
引用
javadocs
:
计数信号灯。从概念上讲,信号量维护一组许可。如果需要,每个Acquired()都会阻止,直到有许可证可用,然后再获取。每个release()都添加了一个许可证,可能会释放一个阻止的acquirer。然而,没有使用实际的许可对象;信号量只是保持对可用数字的计数并相应地进行操作。
下面的代码应该可以工作:
// only allow 5 threads to do the expensive work at the same time
private final Semaphore semaphore = new Semaphore(5, true /* fairness */);
...
// this will block if there are already 5 folks doing the expensive work
semaphore.acquire();
try {
doExpensiveWork();
} finally {
// always do the release in a try/finally to ensure the permit gets released
// even if it throws
semaphore.release();
}