首页 > 编程语言 >Java并发--sleep()、wait()、notify()、notifyAll()方法详解

Java并发--sleep()、wait()、notify()、notifyAll()方法详解

时间:2023-05-25 23:44:32浏览次数:42  
标签:Java thread get -- notifyAll sleep lock println wait

sleep()和wait方法比较 

基本差别:

1,sleep是Thread类中的native方法、wait是Object类中的方法。

/**
 * Causes the currently executing thread to sleep (temporarily cease
 * execution) for the specified number of milliseconds, subject to
 * the precision and accuracy of system timers and schedulers. The thread
 * does not lose ownership of any monitors.
 *
 * @param  millis
 *         the length of time to sleep in milliseconds
 *
 * @throws  IllegalArgumentException
 *          if the value of {@code millis} is negative
 *
 * @throws  InterruptedException
 *          if any thread has interrupted the current thread. The
 *          <i>interrupted status</i> of the current thread is
 *          cleared when this exception is thrown.
 */
public static native void sleep(long millis) throws InterruptedException;
/**
 * Causes the current thread to wait until it is awakened, typically
 * by being <em>notified</em> or <em>interrupted</em>.
 * <p>
 * In all respects, this method behaves as if {@code wait(0L, 0)}
 * had been called. See the specification of the {@link #wait(long, int)} method
 * for details.
 *
 * @throws IllegalMonitorStateException if the current thread is not
 *         the owner of the object's monitor
 * @throws InterruptedException if any thread interrupted the current thread before or
 *         while the current thread was waiting. The <em>interrupted status</em> of the
 *         current thread is cleared when this exception is thrown.
 * @see    #notify()
 * @see    #notifyAll()
 * @see    #wait(long)
 * @see    #wait(long, int)
 */
public final void wait() throws InterruptedException {
    wait(0L);
}

2,sleep方法可以在任何地方使用,wait方法只能在synchronized方法或者synchronized块中使用。

 

主要区别:

1,Thread.sleep 只会让出cpu,不会导致锁行为改变。

2,Object.wait 不仅会让出cpu,还会释放占用的同步资源锁。其他线程可以得到锁。

wait传

 

demo:

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(1000); //等待1000ms,让出cpu、锁
                        System.out.println("thread A is done");
                    } catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        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);
                        System.out.println("thread B is done");
                    } catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }
}

执行结果:

thread A is waiting to get lock
thread A get lock
thread B is waiting to get lock //A 的sleep方法不让出锁。B等待
thread A do wait method //A wait方法 让出锁,A
thread B get lock //A让出锁 B获得锁
thread B is sleeping 10 ms 
thread B is done //B执行完毕
thread A is done //A的wait(1000),到期自动唤醒,正好B释放锁。A可以得到锁

 可以看到,A虽然执行sleep方法,让出CPU,但不让出锁。如果不执行wait(1000)方法,B会一直等待获取锁。

wait方法,必须写在synchronized,因为必须要先获取锁,才能去释放锁。

 

 notify(),notifyAlll()方法:

上面demo中,通过wait(1000),设置参数1000ms后,A线程会自动唤醒。

也可以直接用wait(),不设置自动唤醒,可以在B线程中使用Object.notify()唤醒A线程。

demo:

 

 

两个概念(针对对象):

锁池entryList。B线程被阻塞,进入该对象的锁池,等待锁的释放,多个不同优先级的线程竞争锁,优先级高获取锁的概率大。

等待池WaitSet。不会去竞争锁。A调用wait()方法,会释放该对象的锁,同时进入等待池中,不竞争锁。

 

标签:Java,thread,get,--,notifyAll,sleep,lock,println,wait
From: https://www.cnblogs.com/lukelhi/p/17433214.html

相关文章

  • 5.25 3.3
    一、问题 二、分析三、代码#include<iostream>usingnamespacestd;voidmain(){ longmul,number,k,a,b; cout<<"Itexistsfollowingautomorphicnmberssmallthan100000:"<<endl; for(number=0;number<100000;number++) { for(mul=number,k=1;(......
  • 时间序列-1
    时间序列是与时间相关的、一般按时间顺序的一组数字序列。按平稳行可分为平稳时间序列和非平稳时间序列。对于平稳时间序列,一般可以通过ARMA模型进行拟合。对于非平稳时间序列,可以通过差分转化为非平稳时间序列。个人理解:在深度学习中,时间序列因为其含有稀疏特征而可能造成......
  • 个位数统计
    L1-003个位数统计给定一个 k 位整数 N=dk−1​10k−1+⋯+d1​101+d0​ (0≤di​≤9, i=0,⋯,k−1, dk−1​>0),请编写程序统计每种不同的个位数字出现的次数。例如:给定 N=100311,则有2个0,3个1,和1个3。输入格式:每个输入包含1个测试用例,即一个不超过1000位......
  • Vue CLI配置
    全局安装首先配置淘宝镜像cmd打开,输入npmconfigsetregistryhttps://registry.npm.taobao.org 安装命令npminstall-g@vue/cli发现报错如下,没有权限!!使用管理员模式。 重新开始,完美!! 然而输入查看vue 发现错误信息:系统禁止运行脚本接下来参考文章进行解除进......
  • WSL 启动Ubuntu18.04默认设置网络和开启SSH
    1、wsl-ip.bat脚本@echoonREM先关闭虚拟子系统wsl--shutdownREM以下的Ubuntu为第2步查到的Linux子系统名称REMIP地址根据自己的需要配置wsl-dUbuntu-18.04-urootipaddrdel$(ipaddrshoweth0^|grep'inet\b'^|awk'{print$2}'^|head-n1)deveth0w......
  • 基于TPC算法的WSN网络资源分配matlab仿真
    1.算法仿真效果matlab2022a仿真结果如下:2.算法涉及理论知识概要一个移动通信系统面临的主要问题有三个:由哪些资源组成,资源如何分配?这些资源如何组织形成一个网络,网络架构是什么样子的?各网络组成部分之间如何进行信息交互?资源及资源分配、网络架构、信息交互是移动通信系统运行......
  • iOS MachineLearning 系列(18)—— PoseNet,DeeplabV3与FCRN-DepthPrediction模型
    iOSMachineLearning系列(18)——PoseNet,DeeplabV3与FCRN-DepthPrediction模型本篇文章将再介绍三个官方的CoreML模型:PoseNet,DeeplabV3和FCRN-DepthPrediction。PoseNet是人体姿势分析模型,可以识别图片中的人体部分,然后以17个基准点来描述人体的姿势。关于人体姿势的识别,其实Vision......
  • 实验6
    //task4:#include<stdio.h>#include<string.h>#defineN100typedefstruct{charnum[10];//学号ints1;//期末成绩ints2;//平时成绩doublesum;//总评charlevel[10];//等级}STU;......
  • 浅谈云服务器有哪些优点?
    目前,云服务器大有赶超虚拟主机、VPS和传统物理服务器,成为最具潜力占领互联网服务托管平台市场最大份额的新兴IT部署模式。最近,各大云服务商纷纷推出低价云服务器、免费试用、免费领取等活动,并在各大媒体投放大量广告,谋求占据更高的市场份额。那么,云服务器到底有哪些优势?归根到底,云......
  • CS9027兼容DRV8812,CS9029兼容DRV8841,双通道H桥电机驱动芯片
    CS9027C为打印机和其它电机一体化应用提供一种双通道集成电机驱动方案。CS9027C有两路H桥驱动,每个H桥可提供最大输出电流2A(在24V和Ta=25C适当散热条件下),可驱动两个刷式直流电机,或者一个双极步进电机,或者螺线管或者其它感性负载。双极步进电机可以以整步、2细分、4细分运行,或者......