当我以静态方式同步块调用wait()时,为什么Java抛出java.lang.IllegalMonitorStateException? [英] Why Java throw java.lang.IllegalMonitorStateException when I invoke wait() in static way synchronized block?

查看:42
本文介绍了当我以静态方式同步块调用wait()时,为什么Java抛出java.lang.IllegalMonitorStateException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么Java会在此代码中从主题抛出异常.有人可以解释一下吗?

  class Wait实现Runnable{公共无效run(){同步(Object.class){尝试 {while(true){System.out.println("Before wait()");等待();System.out.println("After wait()");}} catch(InterruptedException e){e.printStackTrace();}}}}公共类ObjectMethodInConcurency{公共静态void main(String [] args){等待w =新的Wait();(新线程(w)).start();}} 

解决方案

在类中使用同步(this){代替 synchronized(Object.class)

编辑

上面代码中的IllegalMonitorException背后的原因

在Java中,使用synced关键字是一种创建和获取监视对象的方法,该监视对象将用作锁来执行相应的代码块.

在上面的代码中,监视程序为"Object.class".

并且wait()方法告诉当前线程等待,直到通知它为止,并且您必须在拥有锁的监视对象上调用wait().

因此调用wait()方法的方式如下所示,否则您将获得IllegalMonitorException.

  synchronized(monitor){monitor.wait();} 

因此对于您的示例,您可以使用"Object.class.wait()" 或将监视器更改为 this ,因为您正在调用 wait()当前实例上的方法

I do not understand why Java throw exception from subject in this code. Could somebody explain me it?

class Wait implements Runnable
{
    public void run() {
        synchronized (Object.class) {
            try {
                while(true) {
                    System.out.println("Before wait()");
                    wait();
                    System.out.println("After wait()");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ObjectMethodInConcurency 
{
    public static void main(String[] args) {
        Wait w = new Wait();
        (new Thread(w)).start();
    }
}

解决方案

Use synchronized (this) { instead of synchronized (Object.class) in your class

EDIT

Reasoning behind the IllegalMonitorException in above code

In Java using synchronized keyword is a way to create and obtain a monitor object which will be used as lock to execute corresponding code block.

In the above code that monitor is "Object.class".

And wait() method tells the current thread to wait until it is notifyed and you have to invoke wait() on the monitor object which owns the lock.

So the way to invoke wait() method is like below otherwise you will get IllegalMonitorException.

synchronized(monitor){
    monitor.wait();
}

So for your example you can either use "Object.class.wait()" or change the monitor to this since you are calling wait() method on the current instance

这篇关于当我以静态方式同步块调用wait()时,为什么Java抛出java.lang.IllegalMonitorStateException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆