java中的sleep()和wait()的区别

news/2025/2/26 13:26:21

转自:https://www.cnblogs.com/hongten/p/hongten_java_sleep_wait.html

对于sleep()方法,我们首先要知道该方法是属于Thread类中的。而wait()方法,则是属于Object类中的。

sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。

在调用sleep()方法的过程中,线程不会释放对象锁。

而当调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备

获取对象锁进入运行状态。

什么意思呢?

举个列子说明:

/**
 * 
 */
package com.b510.test;

/**
 * java中的sleep()和wait()的区别
 * @author Hongten
 * @date 2013-12-10
 */
public class TestD {

    public static void main(String[] args) {
        new Thread(new Thread1()).start();
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        new Thread(new Thread2()).start();
    }
    
    private static class Thread1 implements Runnable{
        @Override
        public void run(){
            synchronized (TestD.class) {
            System.out.println("enter thread1...");    
            System.out.println("thread1 is waiting...");
            try {
                //调用wait()方法,线程会放弃对象锁,进入等待此对象的等待锁定池
                TestD.class.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("thread1 is going on ....");
            System.out.println("thread1 is over!!!");
            }
        }
    }
    
    private static class Thread2 implements Runnable{
        @Override
        public void run(){
            synchronized (TestD.class) {
                System.out.println("enter thread2....");
                System.out.println("thread2 is sleep....");
                //只有针对此对象调用notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。
                TestD.class.notify();
                //==================
                //区别
                //如果我们把代码:TestD.class.notify();给注释掉,即TestD.class调用了wait()方法,但是没有调用notify()
                //方法,则线程永远处于挂起状态。
                try {
                    //sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,
                    //但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。
                    //在调用sleep()方法的过程中,线程不会释放对象锁。
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("thread2 is going on....");
                System.out.println("thread2 is over!!!");
            }
        }
    }
}

 

运行效果:

enter thread1...
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!
thread1 is going on ....
thread1 is over!!!

 

如果注释掉代码:

TestD.class.notify();
 

运行效果:

enter thread1...
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!

 

且程序一直处于挂起状态。

 

========================================================


http://www.niftyadmin.cn/n/543234.html

相关文章

浅谈软件创新之处

微信小游戏——跳一跳 作为一个PC端的小程序,微信跳一跳曾一度被刷爆朋友圈,成为最受欢迎的小游戏,它无疑是很成功的。游戏简单,容易上手。那么它如此受欢迎的原因或者说它和其他游戏相比优势和创新在何处呢?首先&…

[TypeScript] TypeScript对象转JSON字符串范例

[TypeScript] TypeScript对象转JSON字符串范例 Playground http://tinyurl.com/njbrnrvSamples class DataTable {public columns: Array<string> new Array<string>();public rows: Array<DataRow> new Array<DataRow>(); }class DataRow {public c…

自定义RecyclerView,实现ListView、GridView、ViewPager功能

CommonRecyclerView 通用的RecyclerView&#xff0c;实现了RecyclerView、GridView、ViewPager功能 How to To get a Git project into your build: Step 1. Add the JitPack repository to your build file gradle maven sbt leiningen Add it in your root build.gradle …

使用PowerShell Direct从Hyper-V主机管理VM

使用PowerShell Direct从Hyper-V主机管理VM借助PowerShell Direct&#xff0c;我们可以无需担心网络或防火墙限制&#xff0c;因为无论网络还是远程管理配置&#xff0c;它都可以工作。那么&#xff0c;很多朋友都会问既然不是通过网络和防火墙那是通过什么样的方式连接的呢&am…

MeteoInfoLab脚本示例:计算涡度、散度

用U/V分量数据计算涡度和散度&#xff0c;计算涡度的函数是hcurl&#xff0c;计算散度的函数是hdivg&#xff0c;参数都是U, V。脚本程序&#xff1a; f addfile(D:/Temp/GrADS/model.ctl) u f[U][0,0,:,:] v f[V][0,0,:,:] vort hcurl(u, v) divg hdivg(u, v) axesm() ml…

Acrtivity和Application的Context的区别

1. Applicaiton的构造只有一个 public Application() {super(null); } 其父类是ContextWrapper&#xff0c;构造只有一个 Context mBase;public ContextWrapper(Context base) {mBase base; } 由此可见&#xff0c;super里面传进去的是null&#xff0c;Applicaiton是不存在…

一步一步实现一个符合PromiseA+规范的Promise库(1)

今天我们来自己手写一个符合PromiseA规范的Promise库。大家是不是很激动呢&#xff1f;&#xff1f; 才没有。。 我们都知道。在现在的前端开发中&#xff0c;Promise这个东西基本上所有的开发中都会用到。 那必然有些萌新就会问了&#xff0c;Promise到底是个什么东西呢。 按照…

jQuery发送ajax请求三种方式

<button>点击发送ajax get请求</button> <button>点击发送ajax post请求</button> <button>点击发送通用的ajax请求</button> <script type"text/javascript" src"jquery-1.8.3.min.js"></script> <sc…