繁体   English   中英

Java 8 重入锁和条件导致 IllegalMonitorStateException:当前线程不是所有者

[英]Java 8 Reentrant Lock and Condition results in IllegalMonitorStateException: current thread is not owner

我已经在这里搜索了这个错误,但我认为我的一段代码看起来是正确的:

  1. 我在 try..finally 之外获得了锁
  2. 我在 finally 部分有一个解锁
  3. 我只是试图等待锁内的条件。
  4. 我什至打印当前锁是否由该线程持有并返回 true。

这是代码的摘录,如果我试图运行代码,我会得到一个 java.lang.IllegalMonitorStateException: current thread is not owner。 错误在 cond.wait() 方法中。

public void takeARest() {
    lock.lock();
    try {
        while (disembark < totalPassengers) {
            System.err.printf("Held by %s%n",lock.isHeldByCurrentThread());
            cond.wait();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}

有任何想法吗?

为此,您需要Condition.await()

Object.wait()是一种不同的方法,它需要保持对象的监视器(在调用周围的synchornized(cond){}

所以:

public void takeARest() {
    lock.lock();
    try {
        while (disembark < totalPassengers) {
            System.err.printf("Held by %s%n",lock.isHeldByCurrentThread());
            cond.await();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM