简体   繁体   中英

Why do I get IllegalMonitorException in a synchronized block?

public static void main(String[] args) {
        String resource1 = "ratan jaiswal";
        Thread t1 = new Thread() {
            public void run() {
                synchronized (resource1) {
                    System.out.println("Thread 1: locked resource 1");
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        };

        Thread t2 = new Thread() {
            public void run() {
                synchronized (resource1) {
                    System.out.println("Thread 2: locked resource 2");
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                }
            }
        };

        t1.start();
        t2.start();
    }

After I run this code I get line 16 is the line with the wait() call

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at ThreadSyncFromMark.deadlock.dead$1.run(dead.java:16)

Why I get this exception as I see everything is OK here because t1 owns the monitor of resource1 when it call wait

Why I get this exception as I see everything is OK here because t1 owns the monitor of resource1 when it call wait

Yes, t1 owns the monitor of resource1 . But you're not calling resource1.wait() , you're calling this.wait() .

You need to synchronize , wait() and notify() all on the same object (monitor) to make things work the way they should.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM