首页 > 解决方案 > 通知异常 java.lang.IllegalMonitorStateException Locks

问题描述

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

等待方法释放锁,因此线程B可以执行和从线程B我正在为线程A调用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();

    }
}

标签: javamultithreadingconcurrencythread-safetyjava-threads

解决方案


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

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

推荐阅读