2011-04-05 85 views
3

java.lang.IllegalMonitorStateException是我得到一個討厭的堆棧跟蹤。Java問題 - 線程鎖和條件

final Condition[] threads = new Condition[maxThreads]; 
myclass() 
{ 
for (int i =0; i<maxThreads; i++) 
      threads[i] = mutex.newCondition(); 
}  
public void test() 
{ 

mutex.lock(); 
    int id = threadCount; 
    threadCount++; 
mutex.unlock(); 
threads[id].await(); 
} 

當我使用多線程調用測試時,它會生成上面的錯誤。它是由等待線引起的。由於我希望所有線程都能夠等待,所以我很猶豫要用synchronized。

+0

什麼是'mutex'? – 2011-04-05 01:07:21

+0

@Mike Daniels:'mutex'被認爲是'Lock'對象。 – mre 2011-04-05 01:17:23

回答

3

只有當您持有互斥鎖時,才能調用await。因此,代碼應該是:

mutex.lock(); 
try { 
    // do your stuff 
    threads[id].await(); 
} finally { 
    mutex.unlock(); 
} 

我加入了嘗試/最後是保證,即使你拋出一個異常,鎖被釋放的原因。

也可能值得注意的是,您只能在您鎖定互斥鎖的同時針對您的條件調用signal。即使您在調用await之前獲得了鎖,您也可以獲得對該互斥鎖的鎖定,因爲調用await會導致等待的線程在等待時釋放它的鎖。

+0

你的回答是正確的,但我感覺像是在闡述。希望你不介意! :) – mre 2011-04-05 01:14:21

+0

@noob我在同一時間正在闡述它的樣子:o,你的+1 – 2011-04-05 01:14:48

3

在實踐中,你應該await這樣:

mutex.lock(); 
try 
{ 
    threads[threadCount++].await(); 
} 
finally 
{ 
    mutex.unlock(); 
}