java.lang.IllegalMonitorStateException is what I get with a nasty stack trace.
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();
}
When I call test with multiple threads it generates the error above. It is caused by the开发者_JAVA技巧 await line. I am hesitant to used synchronized because I want all threads to be able to await.
You can only call await WHILE you hold the lock on mutex. So the code should be:
mutex.lock();
try {
// do your stuff
threads[id].await();
} finally {
mutex.unlock();
}
The reason I added the try / finally is to ensure that the lock is released even if you throw an exception.
It is probably also worth noting that you can only call signal
on your conditions while holding the lock on mutex as well. You are able to get a lock on the mutex, even though you got a lock before calling await, because calling await
causes the waiting thread to release its lock while it waits.
In practice, you should await
as such:
mutex.lock();
try
{
threads[threadCount++].await();
}
finally
{
mutex.unlock();
}
精彩评论