通知异常java.lang.IllegalMonitorStateException锁

问题描述 投票:0回答:1

我正在尝试等待通知的情况,得到->调用notify时,线程“ Thread-1” java.lang.IllegalMonitorStateException中的异常。

wait方法释放了锁,所以线程B可以执行线程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();

    }
}

java multithreading concurrency thread-safety java-threads
1个回答
0
投票

您正在调用wait并在显式锁定对象上进行通知,这是不合法的。如果使用显式锁定对象,则必须使用与其关联的Condition对象。然后,您应该调用condition.awai t和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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.