【发布时间】:2011-03-22 17:13:21
【问题描述】:
我有一个回调,我想执行一次。为了争论,假设它看起来像这样:
final X once = new X(1);
Runnable r = new Runnable() {
@Override public void run() {
if (once.use())
doSomething();
}
}
其中 X 是一些具有以下行为的并发对象:
构造函数:X(int N) -- 分配 N 个使用许可
boolean use():如果至少有1个使用许可,消费其中一个并返回true。否则返回假。这个操作对于多线程来说是原子的。
我知道我可以为此使用java.util.concurrent.Semaphore,但我不需要它的阻塞/等待方面,我希望这是一次性使用的东西。
AtomicInteger 看起来不够用,除非我做类似的事情
class NTimeUse {
final private AtomicInteger count;
public NTimeUse(int N) { this.count = new AtomicInteger(N); }
public boolean use() {
while (true)
{
int n = this.count.get();
if (n == 0)
return false;
if (this.count.compareAndSet(n, n-1))
return true;
}
}
我对 while 循环感到不安。
CountDownLatch 不起作用,因为 countDown() method 没有返回值,并且不能使用 getCount() 原子地执行。
我应该只使用 Semaphore 还是有更合适的类?
【问题讨论】:
-
你链接到
java.util.concurrent.Semaphore而不是java.util.concurrent.CountDownLatch。 -
在哪里?我有两个超链接,它们看起来很合适。
标签: java countdownlatch