gpt4 book ai didi

java - 我可以通过参数同步方法吗

转载 作者:行者123 更新时间:2023-12-03 12:46:42 24 4
gpt4 key购买 nike

我可以通过参数同步方法吗?

例如 - 我让 person 使用某种方法,我想为 person 做一些操作,但是如果很少有线程为同一个人调用这个方法,我想一个一个地做。

private void dosomething(Long id, Person person) {
dosomethingelse(id, person);
}

如何只对同一个id逐一调用dosomethingelse(id, person)?但我希望这段针对不同 id-s 的代码可以被多线程调用

我写了这段代码,但也许这里有问题或者可以做得更好。

public static class LatchByValue <T> {
public void latch(T value, ConsumerWithException<T> consummer) throws Exception {
CountDownLatch latch = new CountDownLatch(1);
try {
CountDownLatch previousLatch = null;
// we are checking if another thread is already calling this method with the same id
// if sync has CountDownLatch so another thread is already calling this method
// or we put our latch and go on
while ((previousLatch = sync.putIfAbsent(value, latch)) != null) {
try {
// we are waiting for another thread, we are waiting for all threads that put their latch before our thread
previousLatch.await();
} catch (InterruptedException e) {
return;
}
}
consummer.accept(value);
} finally {
latch.countDown();
sync.remove(value, latch);
}
}
private ConcurrentHashMap<T, CountDownLatch> sync = new ConcurrentHashMap<>();
}

例子:

LatchByValue<Long> latch = new LatchByValue<>();

private void dosomething(Long id, Person person) {
latch.latch(
id,
currentId -> { dosomethingelse(currentId, person); }
);
}

最佳答案

使用 CountdownLatch 的问题在于您无法“增加”计数,因此您需要在使用时替换现有的锁存器,这会使代码复杂化。

您可以改为使用 a Semaphore只需一个许可证,您就可以以更简单的方式做同样的事情。

Semaphore s = sync.computeIfAbsent(value, x -> new Semaphore(1, true));
s.acquire(); //this blocks and throws InterruptedException, which you need to handle
try {
consummer.accept(value);
} finally {
s.release();
}

关于java - 我可以通过参数同步方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52501642/

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