gpt4 book ai didi

java - java中的ReentrantLock条件等待获取IllegalMonitorStateException

转载 作者:行者123 更新时间:2023-11-30 03:29:43 25 4
gpt4 key购买 nike

我的应用程序将持续监视一个文件夹,一旦它不为空,就会唤醒工作线程。等待时会抛出 IllegalMonitorStateException 。

原因是什么?

import java.io.File;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.io.FileUtils;

public class LockTest {

public static void main(String[] args) {
String folder = "C:\\temp\\test";

final ReentrantLock messageArrivedLock = new ReentrantLock();
final Condition messageArrivedCondition = messageArrivedLock.newCondition();

Thread workerThread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("worker thread is running");
messageArrivedLock.lock();
while (true) {
System.out.println("worker thread is waiting");
try {
messageArrivedCondition.wait(); //Exception here
System.out.println("worker thread wakes up");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (messageArrivedLock.isHeldByCurrentThread()) {
messageArrivedLock.unlock();
}

}
}
}
});

workerThread.start();

while (true) {
long size = FileUtils.sizeOf(new File(folder));
System.out.println("size:" + size); // 1000

messageArrivedLock.lock();

try {
if (size > 0) {
messageArrivedCondition.signalAll();
}
} finally {
if (messageArrivedLock.isHeldByCurrentThread()) {
messageArrivedLock.unlock();
}

}

}

}

}

最佳答案

我假设您打算调用Condition#await ,通常(如此处的情况)具有与 Object#wait 相同的行为。

The current thread is assumed to hold the lock associated with this Condition when this method is called. It is up to the implementation to determine if this is the case and if not, how to respond. Typically, an exception will be thrown (such as IllegalMonitorStateException) and the implementation must document that fact.

大概你的while循环迭代了一次,释放了finally内的锁。在第二次迭代中,您的线程没有锁,因此调用 wait 将抛出 IllegalMonitorStateException。您的线程需要拥有锁才能在关联的Condition上调用await

您可以在 while 循环中获取锁。

关于java - java中的ReentrantLock条件等待获取IllegalMonitorStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29351588/

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