IllegalMonitorStateException in code

前端 未结 3 735
南笙
南笙 2021-01-16 10:32
class Test {

    public static void main(String[] args) {

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

            System.out.println(\"2..         


        
相关标签:
3条回答
  • 2021-01-16 10:55

    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.

    0 讨论(0)
  • 2021-01-16 11:00

    Hi ankit i assume you are trying to learn some basic concepts of multithreading. try to get hold of some good online tutorials :http://www.javaworld.com/jw-04-1996/jw-04-threads.html

    or try some basic good book. http://www.amazon.com/SCJP-Certified-Programmer-Java-310-065/dp/0071591060/

    The program you wrote actually doesn't need synchronization as there is only one thread (main). I know you are just trying your hands, therefore giving some insights. Even if you correctly called wait method on args(args.wait()) or synchronized on Thread.currentThread your thread may goes into indefinite wait (making your program unresponsive) because there is no other thread to notify your main thread.

    0 讨论(0)
  • 2021-01-16 11:03

    From IllegalMonitorStateException documentation

    Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor

    From Object#notify() documentation

    A thread becomes the owner of the object's monitor in one of three ways:

    • By executing a synchronized instance method of that object.
    • By executing the body of a synchronized statement that synchronizes on the object.
    • For objects of type Class, by executing a synchronized static method of that class.

    So since thread is executing block synchronized on args object

    synchronized (args) {
        //...
    }
    

    you should call args.wait() instead Thread.currentThread().wait(); .

    0 讨论(0)
提交回复
热议问题