多线程问题中,经常问的一点就是sleep方法和wait方法的区别,如果没有看过源码,估计很多人死记硬背理解不了,还是老规矩,看源码理解。
1 注释的源码
Sleep
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
导致当前执行的线程休眠(暂时停止执行)指定的时间...线程不丢失任何监视器的所有权(我坐在座位上睡个觉,尽管我什么都不做但是座位还是我的)
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, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
造成当前线程阻塞直到下面四种情况发生才会被打破阻塞状态:其他线程调用notify或者是notifyAll方法,或者其他线程干扰此线程,或者已经度过线程阻塞的时间。
这个时候就能看到两者的区别了,wait当前线程必须有对象的监视器,线程释放对监视器的所有权直到下面两种情况发生的时候才可以解除阻塞状态。
…
线程继续等待直到他重新获得对监视器的所有权才可以恢复运行。(我出去走走座位给别人坐了,等我回来之后等别人坐完我才可以坐)
2 代码的源码
Thread中静态方法:有java实现的
public static void sleep(long millis, int nanos)
throws InterruptedException{}
Object类中final native方法:需要C底层编写
public final native void wait() throws InterruptedException