Java 同步变量的读取

Java 同步变量的读取,java,multithreading,Java,Multithreading,我不知道该怎么做。我有一个限制: 最多有5个线程可以同时读取一个变量,其他线程必须等待,直到可以再次读取该变量 public void methodA(){ lockI.lock(); 试一试{ while(countIreaders==5 | | modify){ 条件I.等待(); } countIreaders++; }捕捉(中断异常e){ e、 printStackTrace(); }最后{ 如果(条件){ countIreaders=0; lockI.unlock(); 条件i.n

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

  • 最多有5个线程可以同时读取一个变量,其他线程必须等待,直到可以再次读取该变量
public void methodA(){
lockI.lock();
试一试{
while(countIreaders==5 | | modify){
条件I.等待();
}
countIreaders++;
}捕捉(中断异常e){
e、 printStackTrace();
}最后{
如果(条件){
countIreaders=0;
lockI.unlock();
条件i.notifyAll();
}否则{
lockI.unlock();
}
}
}

使用这段代码,我将其设置为串行,但这不是我想要实现的。如何修改代码?

我不太理解您的代码,但您的a所寻找的似乎是a。信号量对于线程同步很有用。您可以使用5个令牌/许可创建一个新的信号量。像这样:

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
}

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

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
}

为什么在finally块中将
countireders
设置为0?您能澄清一下为什么有多少读者在阅读吗?这听起来像是“如何在java中使用synchronized关键字”。这是我的一个约束,很重要。@L.Butz我不必同步任何内容。我用这种方法访问10000个线程,只有5个线程可以读取,使用syncronize,它与我写的相同。为什么在finally块中将
countIreaders
设置为0?你能澄清为什么有多少读卡器在读取它很重要吗?这闻起来像“如何在java中使用synchronized关键字”。这是我的一个约束条件,这很重要。@L.Butz我不需要同步任何东西。我用这种方法访问10000个线程,只能读取5个,使用syncronize时,它与我写的相同。