如果你没有接触过java的多线程,那么多对于这两个方法可能有点陌生,看名字好像这两个方法是差不多的,但是实际上面差别好大。
首先我们看一下官方的API
Sleep(sleep有两个方法,另一个方法传递两个参数,还有一个参数也是时间,只不过是纳秒级别的,所以和这个方法几乎一样,所以这里只分析这个毫秒级别的方法)
public static void sleep(long millis) throws InterruptedException
首先是个静态的方法,入参是一个毫秒数,会抛出InterruptedException异常
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.
让当前执行的线程睡眠(临时停止执行)一段毫秒数的时间,这个时间的精确性受到系统计时器和程序调度精度影响。这个线程不会失去任何监视器的所有权。
wait(也有多个方法,就不一一介绍了)
public final void wait()throws InterruptedException
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).
让当前进程等待直到另一个其他的线程代理调用了notify() 方法或者notifyAll() 方法之后。换句话说,这个方法的行为和wait(0)方法是类似的。
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 notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
当前线程一定要有自己对象的监视器。这个线程释放了自己的监视器然后等待直到其他线程换线这个等待线程的监视器,通过notify() 方法或者notifyAll() 方法。然后该线程将等到重新获得对监视器的所有权后才能继续执行。
As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:
synchronized (obj) { while (<condition does not hold>) obj.wait(); ... // Perform action appropriate to condition }
后面对这两个方法做个总结