2014-10-17 77 views
0

我無法弄清楚如何做到這一點。我有這樣的約束:同步讀取變量

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

有了這個代碼,我做了連載,但它不是我想要達到的目標。我如何修改代碼?

+0

爲什麼在終止塊中將'countIreaders'設置爲0? – yunandtidus 2014-10-17 14:57:01

+0

我不明白。 – 2014-10-17 14:58:03

+0

你能否澄清爲什麼它關係到有多少讀者正在閱讀? – Arkadiy 2014-10-17 14:58:25

回答

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 
}