标签导航:

多线程同步中wait()方法导致illegalmonitorstateexception异常的原因是什么?

多线程同步与wait()方法异常详解

本文分析一段旨在实现三个线程交替打印自身ID的代码,并解释其中出现的IllegalMonitorStateException异常。该代码尝试使用共享字符串变量current_thread控制线程执行顺序,但由于不当使用wait()和notifyAll()方法导致错误。

以下为问题代码片段:

package 并发编程.work2;

public class Test {
    private static volatile String CURRENT_THREAD = "A";

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

    static class PrintThreadName implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                synchronized (CURRENT_THREAD) {
                    while (!Thread.currentThread().getName().equals(CURRENT_THREAD)) {
                        try {
                            CURRENT_THREAD.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                    CURRENT_THREAD = CURRENT_THREAD.equals("A") ? "B" : (CURRENT_THREAD.equals("B") ? "C" : "A");
                    CURRENT_THREAD.notifyAll();
                }
            }
        }
    }
}

异常原因分析:

代码的核心问题在于current_thread变量的用法。代码试图将current_thread用作锁对象,并在持有锁的同时修改其值。当一个线程执行current_thread.wait()进入等待状态后,另一个线程修改了current_thread的值。等待线程被唤醒后,它试图在新的current_thread对象上释放锁,而这个对象并非它之前获取锁的对象,因此抛出IllegalMonitorStateException异常。wait()方法要求在持有锁对象的线程上调用,而修改current_thread后,锁对象已改变。

解决方案:

避免在释放锁之前修改锁对象本身。应使用一个独立的、不会被修改的对象作为锁,例如一个Object实例。这样确保所有线程都在同一个锁对象上进行同步操作,避免IllegalMonitorStateException异常。 修改后的代码如下:

package 并发编程.work2;

public class Test {
    private static final Object LOCK = new Object();
    private static volatile String CURRENT_THREAD = "A";

    public static void main(String[] args) {
        // ... (rest of the main method remains the same)
    }

    static class PrintThreadName implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                synchronized (LOCK) { // 使用独立的锁对象LOCK
                    while (!Thread.currentThread().getName().equals(CURRENT_THREAD)) {
                        try {
                            LOCK.wait(); // 在LOCK对象上等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                    CURRENT_THREAD = CURRENT_THREAD.equals("A") ? "B" : (CURRENT_THREAD.equals("B") ? "C" : "A");
                    LOCK.notifyAll(); // 在LOCK对象上唤醒
                }
            }
        }
    }
}

通过使用独立的锁对象LOCK,解决了IllegalMonitorStateException异常,并保证了线程的正确同步。