Search code examples
javamultithreadingwaitsynchronizedjava.util.concurrent

Why is wait inside of synchronized?


Why is wait() inside of a synchronized block? I mean, only one thread will enter the synchronized block, so how can the other thread execute the wait() instruction?


Solution

    1. Synchronized keyword is used for exclusive accessing.
    2. To make a method synchronized, simply add the synchronized keyword to its declaration. Then no two invocations of synchronized methods on the same object can interleave with each other.
    3. Synchronized statements must specify the object that provides the intrinsic lock. When synchronized(this) is used, you have to avoid to synchronizing invocations of other objects' methods.
    4. wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).
    5. notify() wakes up the first thread that called wait() on the same object.

    Example:

    public class ThreadA {
        public static void main(String[] args){
            ThreadB b = new ThreadB();
            b.start();
    
            synchronized(b){
                try{
                    System.out.println("Waiting for b to complete...");
                    b.wait();
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
    
                System.out.println("Total is: " + b.total);
            }
        }
    }
    
    class ThreadB extends Thread{
        int total;
        @Override
        public void run(){
            synchronized(this){
                for(int i=0; i<100 ; i++){
                    total += i;
                }
                notify();
            }
        }
    }
    

    Got it from: http://www.programcreek.com/2009/02/notify-and-wait-example/