首页 > 其他 > 详细

notify和notifAll的区别

时间:2019-12-28 23:35:32      阅读:83      评论:0      收藏:0      [点我收藏+]

1、我们先验证下wait可以用notify和notifyAll来唤醒

如下测试代码:

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");
                        //这句注释掉,thread A is done就不会被打印
                        lock.notify(); // lock.notifyAll();
                       

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

                }
            }
        }).start();
    }
}

  

  执行结果:

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、notify和notifAll的区别

两个概念

锁池EntryList

等待池 WaitSet

 

notify和notifAll的区别

原文:https://www.cnblogs.com/linlf03/p/12113185.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!