当前位置: 首页 > 图灵资讯 > 技术篇> 多线程编程中使用wait方法导致IllegalMonitorStateException异常的原因是什么?

多线程编程中使用wait方法导致IllegalMonitorStateException异常的原因是什么?

来源:图灵教育
时间:2025-03-07 20:40:54

多线程编程中使用wait方法导致illegalmonitorstateexception异常的原因是什么?

wait()在多线程编程中抛出IllegalMonitorStateeexception异常分析

本文分析了一个多线程编程问题:三个线程(a、b、c)按顺序打印五次ID(abcabc...),使用wait()和notifyall()法同步,但抛出illlegalmonitorstateexception异常。

问题描述: 程序使用volatile字符串变量curent_thread控制线程执行顺序,并使用synchronized块和wait()、notifyAll()方法同步。然而,IlllegalMonitorStateexception出现在操作过程中。

代码片段错误:

// 线程打印完成后,设置下一个要打印的线程标志,唤醒其他线程
if (current_thread.equals("a")) {
    current_thread = "b";
} else if (current_thread.equals("b")) {
    current_thread = "c";
} else if (current_thread.equals("c")) {
    current_thread = "a";
}

完整代码(略有修改,易于理解):

package 并发编程.work2;

public class Test {
    private static volatile String current_thread = "A";
    private static final Object lock = new Object();///新锁对象

    public static void main(String[] args) {
        Thread t1 = new Thread(new PrintThreadName("A"), "A");
        Thread t2 = new Thread(new PrintThreadName("B"), "B");
        Thread t3 = new Thread(new PrintThreadName("C"), "C");
        t1.start();
        t2.start();
        t3.start();
    }

    static class PrintThreadName implements Runnable {
        private String threadName;

        public PrintThreadName(String threadName) {
            this.threadName = threadName;
        }

        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                synchronized (lock) { // 使用独立锁定对象
                    while (!current_thread.equals(threadName)) {
                        try {
                            lock.wait(); // 使用独立锁定对象
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(threadName);
                    if (threadName.equals("A")) {
                        current_thread = "B";
                    } else if (threadName.equals("B")) {
                        current_thread = "C";
                    } else {
                        current_thread = "A";
                    }
                    lock.notifyAll(); // 使用独立锁定对象
                }
            }
        }
    }
}

异常原因: wait()持有对象监视器锁时必须调用方法。 原代码中,current_thread作为锁对象,但curent_thread的值在synchronized块中修改。当线程调用wait()进入等待时,current_thread的引用发生了变化。醒来后,线程试图释放锁,但锁的对象不再是当前的curent_thread,导致IlllegalMonitorStateexception。

解决方案: 使用独立的锁对象(如代码中的lock对象)来控制线程同步,避免在持有锁的同时修改锁对象本身。 修改后的代码使用lock对象作为synchronized块的锁和wait()、notifyAll()方法的参数避免了异常。 这保证了wait()方法始终在正确的锁对象上操作。

以上是多线程编程中使用wait方法导致illegalmonitorstateexception异常的原因?详情请关注图灵教育的其他相关文章!