同步读取变量

时间:2014-10-17 14:52:38

标签: java multithreading

我无法弄清楚如何做到这一点。我有这个约束:

  • 最多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();
        }
    }
}

使用这段代码我把它变成了串行,但它并不是我想要实现的。我该如何修改代码?

1 个答案:

答案 0 :(得分:5)

我真的不了解您的代码,但似乎您所寻找的是Semaphore。信号量对于线程同步很有用。您可以使用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
}
相关问题