The difference notify and notifAll

1, we can use to verify the next wait notify and notifyAll to wake up

Test code as follows:

public class WaitSleepDemo {

    public static void main(String[] args) {
        final  Object lock = new Object();
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread A is waiting to get lock");
                synchronized (lock){

                    try {
                        System.out.println("thread A get lock");
                        Thread.sleep(20);
                        System.out.println("thread A do wait method");
                        //无限期的等待
                        lock.wait();
                        //Thread.sleep(1000);
                        System.out.println("thread A is done");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


        //为了让Thread A 先于Thread B执行
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread B is waiting to get lock");
                synchronized (lock){
                    try {
                        System.out.println("thread B get lock");
                        System.out.println("thread B is sleeping 10 ms");
                       Thread.sleep(10);
                       Lock.wait // (10); 
                        System.out.println ( "Thread B IS DONE"); 
                        // phrase commented, thread A is done will not be printed 
                        lock.notify (); // lock.notifyAll (); 
                       

                    } the catch (InterruptedException E) { 
                        e.printStackTrace (); 
                    } 

                } 
            } 
        .}) Start (); 
    } 
}

  

  Results of the:

thread A is waiting to get lock
thread A get lock
thread B is waiting to get lock
thread A do wait method
thread B get lock
thread B is sleeping 10 ms
thread B is done
thread A is done

  

 

2, the difference notify and notifAll

Two concepts

锁池EntryList

Wait pool WaitSet

 

Guess you like

Origin www.cnblogs.com/linlf03/p/12113185.html