欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

基于Java多线程notify与notifyall的区别分析

时间:2021-05-22 08:39:19|栏目:JAVA代码|点击:

当一个线程进入wait之后,就必须等其他线程notify/notifyall,使用notifyall,可以唤醒
所有处于wait状态的线程,使其重新进入锁的争夺队列中,而notify只能唤醒一个。注意,任何时候只有一个线程可以获得锁,也就是说只有一个线程可以运行synchronized 中的代码,notifyall只是让处于wait的线程重新拥有锁的争夺权,但是只会有一个获得锁并执行。

那么notify和notifyall在效果上又什么实质区别呢?
主要的效果区别是notify用得不好容易导致死锁,例如下面提到的例子。

复制代码 代码如下:

public synchronized void put(Object o) {

    while (buf.size()==MAX_SIZE) {

        wait(); // called if the buffer is full (try/catch removed for brevity)

    }

    buf.add(o);

    notify(); // called in case there are any getters or putters waiting

}

复制代码 代码如下:

public synchronized Object get() {

    // Y: this is where C2 tries to acquire the lock (i.e. at the beginning of the method)

    while (buf.size()==0) {

        wait(); // called if the buffer is empty (try/catch removed for brevity)

        // X: this is where C1 tries to re-acquire the lock (see below)

    }

    Object o = buf.remove(0);

    notify(); // called if there are any getters or putters waiting

    return o;

}

所以除非你非常确定notify没有问题,大部分情况还是是用notifyall。

更多详细的介绍可以参看:
http://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again

上一篇:Spark学习笔记 (二)Spark2.3 HA集群的分布式安装图文详解

栏    目:JAVA代码

下一篇:Java List分页功能实现代码实例

本文标题:基于Java多线程notify与notifyall的区别分析

本文地址:http://www.codeinn.net/misctech/126232.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有