代码中的IllegalMonitorStateException [英] IllegalMonitorStateException in code

查看:119
本文介绍了代码中的IllegalMonitorStateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Test {

public static void main(String [] args){

System.out.println(1 ..);
synchronized(args){

System.out.println(2 ..);

try {
Thread.currentThread()。wait();
} catch(InterruptedException e){
// TODO自动生成的catch块
e.printStackTrace();
}

System.out.println(3 ..);
}

}
}

我是获取 IllegalMonitorStateException 监视此代码中的异常。根据我的理解,由于在 args 周围的同步块是字符串数组对象,当前线程必须已经获得了锁,并且使用wait方法,我释放了锁。 / p>

有人可以解释一下这个例外的原因吗?

解决方案

你在 Thread.currentThread()上调用 wait()。在对任何对象调用 wait()之前,您必须拥有同步块 on的同步块此对象的 这个对象。所以缺少的是

  synchronized(Thread.currentThread()){
Thread.currentThread()。wait( );
}

也就是说,调用 wait()不是你应该做的事情,可能表明你还没有理解 wait()是什么,特别是考虑到你没有调用 notify() notifyAll()的任何其他线程。同步传递给main方法的参数也是一个非常奇怪的选择。 wait()是一种非常低级的方法,即使您完全理解它的作用,也应该很少使用。为了更好的答案,你应该解释你真正想要这个代码做什么。


class Test {

    public static void main(String[] args) {

        System.out.println("1.. ");
        synchronized (args) {

            System.out.println("2..");

            try {
                Thread.currentThread().wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("3..");
        }

    }
}

I am getting IllegalMonitorStateException monitor exception in this code. As per my understanding, because of synchronized block around args which is string array object, current thread must have acquired the lock and with the wait method, I am release the lock.

Can someone explain me the reason behind this exception?

解决方案

You're calling wait() on Thread.currentThread(). Before calling wait() on any object, you must own the monitor of this object, by the way of a synchronized block synchronizing on this object. So what is missing is

synchronized(Thread.currentThread()) {
    Thread.currentThread().wait();
}

That said, calling wait() on a Thread object is not something you should do, and probably shows that you have not understood what wait() does, especially given that you don't have any other thread calling notify() or notifyAll(). Synchronizing on the arguments passed to the main method is also a very strange choice. wait() is a very low-level method that should rarely be used, even if you fully understand what it does. For a better answer, you should explain what you actually want this code to do.

这篇关于代码中的IllegalMonitorStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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