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.
*
* @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;
首先我们可以看到sleep方法是一个native方法,也就是本地方法,注意看注释,The thread does not lose ownership of any monitors.,说白了也就是sleep的线程不会丢失对象监视器,也就是不会释放锁。
wait
/**
* Causes the current thread to wait until another thread invokes the
* {@link java.lang.Object#notify()} method or the
* {@link java.lang.Object#notifyAll()} method for this object.
* In other words, this method behaves exactly as if it simply
* performs the call {@code wait(0)}.
* <p>
* 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.
* <p>
* This method should only be called by a thread that is the owner
* of this object's monitor. See the {@code notify} method for a
* description of the ways in which a thread can become the owner of
* a monitor.
*/
public final void wait() throws InterruptedException {
wait(0);
}
public final native void wait(long timeout) throws InterruptedException;
通过源码注释可以看出,调用对象的wait方法会释放掉该线程的对象监视器,说白了就是释放锁。
总结wait和sleep的共同点和区别:
1、都是使线程中断一段时间,并且都是native方法。
2、wait释放锁,sleep不释放锁。
3、wait(>0)和sleep(>0)都是在多少毫秒后苏醒4
4、sleep是Thread的方法,wait是Object的synchronized方法块中的方法
5、调用sleep线程进入runnable状态,而调用wait线程进入阻塞状态