Difference between wait() and sleep()

前端 未结 30 4006
無奈伤痛
無奈伤痛 2020-11-22 00:24

What is the difference between a wait() and sleep() in Threads?

Is my understanding that a wait()-ing Thread is still in runni

30条回答
  •  天命终不由人
    2020-11-22 00:52

    From oracle documentation page on wait() method of Object:

    public final void wait()
    
    1. Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
    2. 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
    3. interrupts and spurious wakeups are possible
    4. This method should only be called by a thread that is the owner of this object's monitor

    This method throws

    1. IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.

    2. InterruptedException - if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.

    From oracle documentation page on sleep() method of Thread class:

    public static void sleep(long millis)
    
    1. 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.
    2. The thread does not lose ownership of any monitors.

    This method throws:

    1. IllegalArgumentException - if the value of millis is negative

    2. InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

    Other key difference:

    wait() is a non-static method (instance method) unlike static method sleep() (class method).

提交回复
热议问题