Wait() / notify() synchronization

前端 未结 3 1187
广开言路
广开言路 2020-12-28 21:31

I\'m trying to check how wait/notify works in java.

Code:

public class Tester {
    public static void main(String[] args) {
                


        
3条回答
  •  被撕碎了的回忆
    2020-12-28 22:20

    Object monitor locks need to be performed a single reference of the same lock...

    In your example you are waiting on an instance of the Thread, but using notify from the Runnable. Instead, you should use a single, common lock object...for example

    public class Tester {
    
        public static final Object LOCK = new Object();
    
        public static void main(String[] args) {
            MyRunnable r = new MyRunnable();
            Thread t = new Thread(r);
            t.start();
            synchronized (LOCK) {
                try {
                    System.out.println("wating for t to complete");
                    LOCK.wait();
                    System.out.println("wait over");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static class MyRunnable implements Runnable {
    
            public void run() {
                System.out.println("entering run method");
                synchronized (LOCK) {
                    System.out.println("entering syncronised block");
                    LOCK.notify();
                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("leaving syncronized block");
                }
                System.out.println("leaving run method");
            }
        }
    }
    

    Output...

    wating for t to complete
    entering run method
    entering syncronised block
    leaving syncronized block
    wait over
    leaving run method
    

    wait over and leaving run method could change positions depending on the thread scheduling.

    You could try putting the sleep out side the synchronized block. This will release the monitor lock allowing the wait section to continue running (as it can't start until the lock is released)

        public static class MyRunnable implements Runnable {
    
            public void run() {
                System.out.println("entering run method");
                synchronized (LOCK) {
                    System.out.println("entering syncronised block");
                    LOCK.notify();
                    System.out.println("leaving syncronized block");
                }
                try {
                    Thread.currentThread().sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("leaving run method");
            }
        }
    

提交回复
热议问题