有关嵌套锁的illegalStateException

时间:2014-11-01 13:00:16

标签: java multithreading

我得到了这个例外,但我不明白为什么。

public Test() {
        globalLock = new ReentrantLock();
        condition = globalLock.newCondition();
    }

public void increaseRow(Integer row) {
    matrixLock.lock();
    try {
        while (countIncreasingColumn > 0)
            condition.await();
        countIncreasingRow++;
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
       condition.notifyAll();
        matrixLock.unlock();
        synchronized (rows.get(row)) {
            for (int j = 0; j < column; j++)
                matrix[row][j] += 1;
            countIncreasingRow--;
        }
    }
}

线程类:

public void run() {
        while (true) {
            test.function(new Random().nextInt(10));
        }
    }

堆栈跟踪:

Exception in thread "Thread-0" waiting thread for test 18
java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)

我在notifyAll()上遇到了例外。执行global.lock()块的线程是所有者,为什么我得到这个?

1 个答案:

答案 0 :(得分:1)

您似乎对 Monitor Lock Object#notifyAll&amp; synchronized - 语句)和条件变量Condition#signalAll感到困惑&amp; Condition#await)。

如果您等待Condition#await,则必须使用Condition#signalAll代替Object#notifyAll

<强>更新 请参阅notifyAll() throws IllegalMonitorStateException以解决OP的问题。