IllegalMonitorStateException

IllegalMonitorStateException

我的应用程序将继续监视文件夹,一旦文件夹不为空,它将唤醒工作线程。 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。您的线程需要拥有锁才能在关联的await上调用Condition

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

09-27 21:34