理解Java中的sleep和wait方法


Java版本:jdk8

前言

在多线程编程学习的时候,由于理解比较粗浅,故作此文章来加深自己对sleep和wait的理解。关于如何把握sleep和wait的区别的关键在于

sleep在Thread中定义,wait在Object中定义。sleep用来操控线程,wait用来操控对象。

官方说明

sleep

  /**
     * 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.
     */
    public static native void sleep(long millis) throws InterruptedException;
  1. 首先,sleep(long millis)是一个在Thread中声明的native方法,由底层的C/C++来实现sleep的功能

  2. sleep方法jdk注释,表达的内容

    a.当前执行的线程进入指定毫秒数的睡眠状态, timed_waiting状态。

    b.当前线程不会丢失对象锁,其他线程依旧无法获取monitor而无法访问对象

**补充 **

Thread.sleep(0);

在线程中,调用sleep(0)可以释放cpu时间,让线程马上重新回到就绪队列而非等待队列,sleep(0)释放当前线程所剩余的时间片(如果有剩余的话),这样可以让操作系统切换其他线程来执行,提升效率。

wait

    /**
     * The current thread must own this object's monitor. The thread
     * releases ownership of this monitor and waits until another thread
     * notifies threads waiting on this object's monitor to wake up
     * either through a call to the {@code notify} method or the
     * {@code notifyAll} method. The thread then waits until it can
     * re-obtain ownership of the monitor and resumes execution.
     */
    public final void wait() throws InterruptedException {
        wait(0);
    }

  1. 首先,wait是Object中声明的native方法,由底层的C/C++实现。

  2. wait方法的jdk注释,表达的内容

    a.当前正在执行的线程必然是已经拥有了对象的监视器,也就是对象锁,意味着wait 使用必须配合synchronized一起使用,而sleep 不用。

    b.wait会让线程释放对Monitor,线程也不可避免的智能进入休眠状态(waiting 状态)。其他线程可以访问该对象。

补充

public final native void wait(long timeout) 

// timeout – the maximum time to wait in milliseconds.
// timeout = 0 永远等待,直到其他线程notify,无限加塞
// timeout > 0 直到其他线程调用此对象的notify()方法或 notifyAll() 方法,或者超过指定的时间量


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM