Java中的wait和sleep
sleep()和wait()
首先,Java中的多线程是一种抢占式的机制,而不是分时机制。抢占式的机制是有多个线程处于可运行状态,但是只有一个线程在运行。
这种机制决定了,对于同一对象的多线程访问,必须考虑同步的问题,synchronize的意义在这。
几个区别:
- sleep是Thread类的方法,用于线程自身的控制;wait是Object类的方法,用于线程之间的控制,配套的方法是Object·的notify和notifyAll方法。
- sleep与锁没有关系,如果在锁之中,不会释放锁。wait存在于锁之中,会释放当前的锁,等待被唤醒(notify)。
- sleep必须捕获异常,而wait,notify和notifyAll不需要捕获异常 。但在 sleep的过程中过程中有可能被其他对象调用它的interrupt(),产生InterruptedException异常,如果你的程序不捕获这个异常,线程就会异常终止,进入TERMINATED状态,如果你的程序捕获了这个异常,那么程序就会继续执行catch语句块(可能还有finally语句块)以及以后的代码。注意sleep()方法是一个静态方法,也就是说他只对当前对象有效,不能通过t.sleep()让t对象进入sleep。
JDK8关于这两个的解释:
/**
* 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;
sleep方法总结为:
使当前运行的线程休眠,该线程不会丢失对任何监视器的所有权。
/**
* 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>
* As in the one argument version, interrupts and spurious wakeups are
* possible, and this method should always be used in a loop:
* <pre>
* synchronized (obj) {
* while (<condition does not hold>)
* obj.wait();
* ... // Perform action appropriate to condition
* }
* </pre>
public final void wait() throws InterruptedException {
wait(0);
}
wait方法总结为:
使当前线程等待,直到另外线程唤醒被锁对象的notify或notifyAll方法。当前线程,必须拥有当前对象的监视器,当wait时,释放这种拥有关系,直到其他线程唤醒此对象的notify或notifyAll方法,此时线程重新获得这种拥有关系,并继续执行。
I am a slow walker, but I never walk backwards.