IllegalMonitorStateException
是 Java 中的一个运行时异常,通常在多线程编程中出现。这个异常表示当前线程在调用 wait()
、notify()
或 notifyAll()
方法时,没有持有该对象的监视器(即锁)。
wait()
和 notify()
方法,线程可以有效地等待某个条件的发生,并在条件满足时被唤醒,从而优化资源的使用。synchronized
关键字修饰的方法。synchronized
关键字修饰的代码块。ConcurrentHashMap
,提供线程安全的集合操作。IllegalMonitorStateException
通常发生在以下情况:
synchronized
关键字:在调用 wait()
、notify()
或 notifyAll()
方法之前,没有使用 synchronized
关键字锁定对象。wait()
或 notify()
方法时,需要锁定类的 Class
对象,而不是实例对象。假设我们有一个静态方法,需要等待某个条件满足:
public class Example {
private static boolean condition = false;
public static synchronized void waitForCondition() throws InterruptedException {
while (!condition) {
wait(); // 这里会抛出 IllegalMonitorStateException
}
System.out.println("Condition is met!");
}
public static synchronized void setCondition(boolean value) {
condition = value;
notifyAll(); // 唤醒等待的线程
}
}
在这个例子中,waitForCondition
方法和 setCondition
方法都使用了 synchronized
关键字,确保在调用 wait()
和 notifyAll()
方法时持有类的监视器。
synchronized
关键字:wait()
、notify()
或 notifyAll()
方法之前,确保当前线程持有对象的监视器。synchronized
关键字锁定类的 Class
对象。wait()
和 notify()
方法。public class Example {
private static boolean condition = false;
public static void waitForCondition() throws InterruptedException {
synchronized (Example.class) {
while (!condition) {
Example.class.wait(); // 正确锁定类的 Class 对象
}
System.out.println("Condition is met!");
}
}
public static void setCondition(boolean value) {
synchronized (Example.class) {
condition = value;
Example.class.notifyAll(); // 正确唤醒等待的线程
}
}
}
通过这种方式,可以避免 IllegalMonitorStateException
异常,并确保线程安全。
领取专属 10元无门槛券
手把手带您无忧上云