gpt4 book ai didi

java - 我的代码抛出 java.lang.IllegalMonitorStateException

转载 作者:行者123 更新时间:2023-12-02 04:48:59 25 4
gpt4 key购买 nike

package threads;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class text implements Runnable {
static Lock lock = new ReentrantLock();

public static void main(String[] args) throws InterruptedException {

testts();
new Thread(new text()).start();

}

static void testts() {
lock.lock();
}

@Override
public void run() {
lock.unlock();

System.out.println("un-locked");
}
}

抛出

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:127)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1175)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:431)
at threads.text.run(text.java:28)
at java.lang.Thread.run(Thread.java:619)

最佳答案

javadoc of ReentrantLock#unlock()

If the current thread is not the holder of this lock then IllegalMonitorStateException is thrown.

您的新线程不拥有该锁,而是主线程拥有。因此,当新线程尝试解锁它没有持有的锁时,会引发异常。

关于java - 我的代码抛出 java.lang.IllegalMonitorStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29424858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com