关闭 x
IT技术网
    技 采 号
    ITJS.cn - 技术改变世界
    • 实用工具
    • 菜鸟教程
    IT采购网 中国存储网 科技号 CIO智库

    IT技术网

    IT采购网
    • 首页
    • 行业资讯
    • 系统运维
      • 操作系统
        • Windows
        • Linux
        • Mac OS
      • 数据库
        • MySQL
        • Oracle
        • SQL Server
      • 网站建设
    • 人工智能
    • 半导体芯片
    • 笔记本电脑
    • 智能手机
    • 智能汽车
    • 编程语言
    IT技术网 - ITJS.CN
    首页 » JAVA »Java的wait(), notify()和notifyAll()使用心得

    Java的wait(), notify()和notifyAll()使用心得

    2015-03-09 00:00:00 出处:投稿
    分享

    本篇文章是对java的 wait(),notify(),notifyAll()进行了详细的分析介绍,需要的朋友参考下。

    wait(),notify()和notifyAll()都是java.lang.Object的方法:
    wait(): Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
    notify(): Wakes up a single thread that is waiting on this object’s monitor.
    notifyAll(): Wakes up all threads that are waiting on this object’s monitor.

    这三个方法,都是Java语言提供的实现线程间阻塞(Blocking)和控制进程内调度(inter-process communication)的底层机制。在解释如何使用前,先说明一下两点:

    1. 正如Java内任何对象都能成为锁(Lock)一样,任何对象也都能成为条件队列(Condition queue)。而这个对象里的wait(), notify()和notifyAll()则是这个条件队列的固有(intrinsic)的方法。

    2. 一个对象的固有锁和它的固有条件队列是相关的,为了调用对象X内条件队列的方法,你必须获得对象X的锁。这是因为等待状态条件的机制和保证状态连续性的机制是紧密的结合在一起的。

    (An object’s intrinsic lock and its intrinsic condition queue are related: in order to call any of the condition queue methods on object X, you must hold the lock on X. This is because the mechanism for waiting for state-based conditions is necessarily tightly bound to the mechanism fo preserving state consistency)

    根据上述两点,在调用wait(), notify()或notifyAll()的时候,必须先获得锁,且状态变量须由该锁保护,而固有锁对象与固有条件队列对象又是同一个对象。也就是说,要在某个对象上执行wait,notify,先必须锁定该对象,而对应的状态变量也是由该对象锁保护的。

    知道怎么使用后,我们来问下面的问题:

    1. 执行wait, notify时,不获得锁会如何?

    请看代码:

    public static void main(String[] args) throws InterruptedException {
            Object obj = new Object();
            obj.wait();
            obj.notifyAll();
    }

    执行以上代码,会抛出java.lang.IllegalMonitorStateException的异常。

    2. 执行wait, notify时,不获得该对象的锁会如何?

    请看代码:

    public static void main(String[] args) throws InterruptedException {
            Object obj = new Object();
            Object lock = new Object();
            synchronized (lock) {
                obj.wait();
                obj.notifyAll();
            }
        }

    执行代码,同样会抛出java.lang.IllegalMonitorStateException的异常。

    3. 为什么在执行wait, notify时,必须获得该对象的锁?

    这是因为,如果没有锁,wait和notify有可能会产生竞态条件(Race Condition)。考虑以下生产者和消费者的情景:

    1.1生产者检查条件(如缓存满了)-> 1.2生产者必须等待

    2.1消费者消费了一个单位的缓存 -> 2.2重新设置了条件(如缓存没满) -> 2.3调用notifyAll()唤醒生产者

    我们希望的顺序是: 1.1->1.2->2.1->2.2->2.3

    但在多线程情况下,顺序有可能是 1.1->2.1->2.2->2.3->1.2。也就是说,在生产者还没wait之前,消费者就已经notifyAll了,这样的话,生产者会一直等下去。

    所以,要解决这个问题,必须在wait和notifyAll的时候,获得该对象的锁,以保证同步。

    请看以下利用wait,notify实现的一个生产者、一个消费者和一个单位的缓存的简单模型:

    public class QueueBuffer {
        int n;
        boolean valueSet = false;
        synchronized int get() {
            if (!valueSet)
                try {
                    wait();
                } catch (InterruptedException e) {
                    System.out.println("InterruptedException caught");
                }
            System.out.println("Got: " + n);
            valueSet = false;
            notify();
            return n;
        }
        synchronized void put(int n) {
            if (valueSet)
                try {
                    wait();
                } catch (InterruptedException e) {
                    System.out.println("InterruptedException caught");
                }
            this.n = n;
            valueSet = true;
            System.out.println("Put: " + n);
            notify();
        }
    }
    public class Producer implements Runnable {
        private QueueBuffer q;
        Producer(QueueBuffer q) {
            this.q = q;
            new Thread(this, "Producer").start();
        }
        public void run() {
            int i = 0;
            while (true) {
                q.put(i++);
            }
        }
    }
    public class Consumer implements Runnable {
        private QueueBuffer q;
        Consumer(QueueBuffer q) {
            this.q = q;
            new Thread(this, "Consumer").start();
        }
        public void run() {
            while (true) {
                q.get();
            }
        }
    }
    public class Main {
        public static void main(String[] args) {
            QueueBuffer q = new QueueBuffer(); 
            new Producer(q); 
            new Consumer(q); 
            System.out.println("Press Control-C to stop."); 
        }
    }

    所以,JVM通过在执行的时候抛出IllegalMonitorStateException的异常,来确保wait, notify时,获得了对象的锁,从而消除隐藏的Race Condition。

    最后来看看一道题:写一个多线程程序,交替输出1,2,1,2,1,2……

    利用wait, notify解决:

    public class OutputThread implements Runnable {
        private int num;
        private Object lock;
        public OutputThread(int num, Object lock) {
            super();
            this.num = num;
            this.lock = lock;
        }
        public void run() {
            try {
                while(true){
                    synchronized(lock){
                        lock.notifyAll();
                        lock.wait();
                        System.out.println(num);
                    }
                }
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        public static void main(String[] args){
            final Object lock = new Object();
            Thread thread1 = new Thread(new OutputThread(1,lock));
            Thread thread2 = new Thread(new OutputThread(2, lock));
            thread1.start();
            thread2.start();
        }
    }
    上一篇返回首页 下一篇

    声明: 此文观点不代表本站立场;转载务必保留本文链接;版权疑问请联系我们。

    别人在看

    Edge浏览器百度被劫持/篡改怎么办,地址后边跟着尾巴#tn=68018901_7_oem_dg

    Google Chrome 在 iPhone 上新增了 Safari 数据导入选项

    Windows 11专业版 KMS工具激活产品密钥的方法

    DEDECMS安全策略官方出品

    Microsoft Text Input Application 可以关闭吗?

    新版本QQ如何关闭自带的浏览器?

    C++编程语言中continue的用法和功能,附举例示范代码

    c++ map 的数据结构、基本操作以及其在实际应用中的使用。

    C语言如何避免内存泄漏、缓冲区溢出、空指针解引用等常见的安全问题

    C语言中的break语句详解

    IT头条

    马斯克2026最新采访总结:2040年,全球机器人数量将突破100亿台

    23:52

    专家解读|规范人工智能前沿业态健康发展的新探索:解读《人工智能拟人化互动服务管理暂行办法》

    00:54

    用至强 6高存力搞定MoE卸载!

    17:53

    美国将允许英伟达向中国“经批准的客户”出售H200 GPU

    02:08

    苹果与微信就15%手续费达成一致?腾讯未置可否

    22:00

    技术热点

    PHP 和 Node.js 的10项对比挑战

    Javascript闭包深入解析及实现方法

    windows 7、windows 8.1手动增加右键菜单功能技巧

    MYSQL出错代码大汇总

    windows 7假死机怎么办 windows 7系统假死机的原因以及解决方法

    Ubuntu(Linux)下配置IP地址的方法

      友情链接:
    • IT采购网
    • 科技号
    • 中国存储网
    • 存储网
    • 半导体联盟
    • 医疗软件网
    • 软件中国
    • ITbrand
    • 采购中国
    • CIO智库
    • 考研题库
    • 法务网
    • AI工具网
    • 电子芯片网
    • 安全库
    • 隐私保护
    • 版权申明
    • 联系我们
    IT技术网 版权所有 © 2020-2025,京ICP备14047533号-20,Power by OK设计网

    在上方输入关键词后,回车键 开始搜索。Esc键 取消该搜索窗口。