class A
{
    synchronized void m1()
    {
        try
        {
            System.out.println(Thread.currentThread().getName()+"inside m1");
            notify();
            DeadlockAvoidance.a2.wait();
            DeadlockAvoidance.a2.m2();
        }
        catch(IllegalMonitorStateException e)
        {
            //System.out.println("IllegalMonitorStateException occured");
        }
        catch(InterruptedException e)
        {
            //System.out.println("IllegalMonitorStateException occured");
        }
    }

    synchronized void m2()
    {
        try
        {
            System.out.println(Thread.currentThread().getName()+"inside m2");
            notify();
            DeadlockAvoidance.a1.wait();
            DeadlockAvoidance.a1.m1();
        }
        catch(IllegalMonitorStateException e)
        {
            System.out.println("IllegalMonitorStateException occured");
        }
        catch(InterruptedException e)
        {
            System.out.println("IllegalMonitorStateException occured");
        }
    }
}

class DeadlockAvoidance
{
    static A a1=new A();
    static A a2=new A();
    public static void main(String[] args)
    {
        System.out.println("Main is running");

        Runnable r1=new Runnable()
                                {
                                    public void run()
                                    {
                                        a1.m1();
                                    }
                                };

        Runnable r2=new Runnable()
                                {
                                    public void run()
                                    {
                                        a2.m2();
                                    }
                                };

        Thread t1=new Thread(r1);
        Thread t2=new Thread(r2);

        t1.setName("Thread-1");
        t2.setName("Thread-2");

        System.out.println("Thread 1 created");
        System.out.println("Thread 2 created");
        t1.start();t2.start();

        System.out.println("main() finished...!!!");
    }
}


================================================== ==============

C:\ Users \ hp \ Desktop \ src \ Day13> java DeadlockAvoidance
主正在运行
创建线程1
创建线程2
main()完成... !!!
线程2 inside m2
线程1内侧m1
发生IllegalMonitorStateException

发生IllegalMonitorStateException

请帮助我解决此异常。

最佳答案

Here's wait()方法的文档,内容如下:


  使当前线程等待,直到另一个线程调用
  此对象的notify()方法或notifyAll()方法。
  
  此方法仅应由拥有者的线程调用
  该对象的监视器。请参阅notify方法以获取有关
  线程可以成为监视器所有者的方式。


因此,为了在对象上调用wait(),必须为该对象要求monitor,可以通过从wait()上下文内部调用synchronized来获取监视器。

问题中的示例在wait()a1实例上调用a2,而它们已经获得了当前实例的锁(而不是a1或a2)。

例如。为了在wait()上调用a2,我们需要编写以下内容:

synchronized(a2){
    DeadlockAvoidance.a2.wait();
}


由于线程在调用wait()时未将锁锁定在a1或a2上,因此会抛出IllegalMonitorStateException

关于java - IlligileMonitorStateException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43559730/

10-15 11:32