通知异常 java.lang.IllegalMonitorStateException 锁

Notify exception java.lang.IllegalMonitorStateException Locks

我正在尝试等待和通知方案,在调用通知时在线程 "Thread-1" java.lang.IllegalMonitorStateException 中出现 --> 异常。

wait 方法释放锁,因此 threadB 可以执行并从 threadB 我正在为 threadA 调用 lock.notify。

你能帮我解决这个问题吗?

class SynchronizedCodee  {

    int a = 5;
    Lock lock = new ReentrantLock();
    public void threadA()
    {
        lock.lock();
        try {
            lock.wait();
            System.out.println("A = "+a);
        } catch (Exception e) {
            // TODO Auto-generated catch block
//          e.printStackTrace();
        }
        finally
        {
            lock.unlock();
        }
    }

    public void threadB()
    {
        if(lock.tryLock())
        {
        this.a = 11;
        System.out.println("B = "+a);
                lock.notify(); // getting erro over here
        }
        else
        {
            System.out.println("didn't managed to get a lock");
        }
    }

}
class ThreadA extends Thread{
    SynchronizedCodee s;
    public ThreadA(SynchronizedCodee s) {
        this.s = s;
    }
    public void run()
    {
        s.threadA();
    }
}

class ThreadB extends Thread{
    SynchronizedCodee s;
    public ThreadB(SynchronizedCodee s) {
        this.s = s;
    }
    public void run()
    {
        s.threadB();
    }
}
public class SynchronizedCode{
    public static void main(String ag[]) throws InterruptedException
    {
        SynchronizedCodee s = new SynchronizedCodee();
        ThreadA t1  = new ThreadA(s);
        ThreadB t2  = new ThreadB(s);
        t1.start();
        Thread.sleep(100);
        t2.start();

    }
}

您在显式锁定对象上调用等待和通知,这是不合法的。如果您正在使用显式锁定对象,则必须使用与其关联的 Condition 对象。那么你应该调用 condition.await 和 condition.signalAll 方法而不是 waitnotify。这是在您的特定场景中使用显式锁的习惯用法。

final Condition setA = lock.newCondition();
public void threadA() {
    lock.lock();
    try {
        while (a == 5)
            setA.await();
        System.out.println("A = " + a);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        lock.unlock();
    }
}

public void threadB() {
    lock.lock();
    try {
        this.a = 11;
        System.out.println("B = " + a);
        setA.signalAll();
    } finally {
        lock.unlock();
    }
}

此程序产生以下输出:

B = 11
A = 11