gpt4 book ai didi

java - 在容器中等待 CountDownLatch 的多个实例

转载 作者:搜寻专家 更新时间:2023-11-01 01:35:13 26 4
gpt4 key购买 nike

我写了一个 CountDownLatchContainer 类,它有一个 await() 方法,等待所有 CountDownLatches。一切正常。

public final class CountDownLatchContainer
{
private final Set<CountDownLatch> countDowns;

public CountDownLatchContainer(List<CountDownLatch> countDowns)
{
this.countDowns = new HashSet<CountDownLatch>(countDowns);
}

public void await() throws InterruptedException
{
for (CountDownLatch count : countDowns)
count.await();
}
}

为了科学和艺术 (:D),我想扩展功能并从 CountDownLatch 添加 public boolean await(long timeout, TimeUnit unit) > 类。

我希望每个倒计时锁存器都具有相同的超时时间,并且整个方法只是为了阻塞 timeout TimeUnits 的数量。我很难做到这一点。我拥有的是:

  public boolean await(long timeout, TimeUnit unit) throws InterruptedException
{
boolean success = true;
for (CountDownLatch count : countDowns)
success &= count.await(timeout / countDowns.size(), unit);
return success;
}

因此,总超时时间得到了处理,但每次倒计时只占总时间的百分比。

那么我如何才能在不超过总时间的情况下为单个锁存器提供与方法参数中指定的相同的时间量?

这是一个可视化。感谢 hexafraction 的 ascii 艺术灵感。

|-----------------------------|
Total
|-----------------------------|
L1
|-----------------------------|
L2
|-----------------------------|

最佳答案

通过等待每个闩锁然后查看剩余时间来工作。

首先等待原始时间的第一个锁存器。注意实际花了多长时间。剩余时间设置为总时间减去花费的时间。现在,在剩余时间的限制下等待下一个闩锁。减去实际。继续直到等待所有 latch 或剩余时间达到 0(由于 latch 在其剩余时间内超时)

|-----------------------------|
Total
|------|----------------------|
L1 Remaining(1)
|------|---------|------------|
L1 L2 Remaining(2)

等等...等待 l1 总计,l2 剩余(1)等

另一种方法是将操作按时间切片成片,例如每片 1 毫秒。循环闩锁(将它们标记为已使用/通过集合的可变副本的迭代器删除它们可能很好)并等待切片长度,直到释放所有闩锁或达到时间。

关于java - 在容器中等待 CountDownLatch 的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18663436/

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