我的应用程序将继续监视一个文件夹,一旦它不为空,它将唤醒工作线程。等待过程中将抛出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
相同的行为。
假设当前线程持有与此相关联的锁调用此方法时为
Condition
。这取决于实施以确定是否是这种情况,如果不是,如何应对。通常,会抛出异常(例如IllegalMonitorStateException
),并且实施必须记录事实。
假设您的while
循环迭代了一次,释放了finally
内部的锁。在第二次迭代中,线程没有锁,因此调用wait
将抛出IllegalMonitorStateException
。您的线程需要拥有锁才能在关联的Condition
上调用await
。
您可以在while
循环中获取锁。