gpt4 book ai didi

java - 同步读取变量

转载 作者:行者123 更新时间:2023-12-01 17:03:49 25 4
gpt4 key购买 nike

我不知道该怎么做。我有这个限制:

  • 最多 5 个线程可以同时读取一个变量,其他线程必须等待直到再次读取该变量。
public void methodA() {
lockI.lock();
try {
while (countIreaders == 5 || modify) {
conditionI.await();
}
countIreaders++;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (condition) {
countIreaders = 0;
lockI.unlock();
conditionI.notifyAll();
} else {
lockI.unlock();
}
}
}

通过这段代码,我将其串行化,但这不是我想要实现的目标。如何修改代码?

最佳答案

我不太明白你的代码,但似乎你正在寻找的是 Semaphore 。信号量对于线程同步很有用。您可以使用 5 个 token /许可证创建一个新信号量。像这样:

Semaphore sem = new Semaphore(5); //initialization in your data structure

//...

public void yourThreadFunction() {
// [...] in your readers threads:
// each thread will of course have to use the same semaphore
// A thread must aquire a token from the semaphore before accessing your variable
sem.aquire(); //this call hangs until a permit is available
// read your value and do some computation
// only 5 threads can be inside this part because of the aquire
sem.release(); // release the token/permits
}

关于java - 同步读取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26427693/

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