IllegalMonitorStateException in code

前端 未结 3 778
南笙
南笙 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 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(); .

提交回复
热议问题