Java中sleep()和wait()区别

(1).Thread.sleep() vs someObject.wait() =>for Thread vs for Object
(2).release lock or not?=>当等待时,wait()会释放lock或者监视器,而sleep不会释放任何lock或者监视器。
/////////////begin//////
synchronized(LOCK) {
    Thread.sleep(1000); // LOCK is held
}


synchronized(LOCK) {
    LOCK.wait(); // LOCK is not held
/////////////end////////
(3).wakeup by self or by other thread=>sleep()时,当前线程停止指定的毫秒数后,又开始执行;而wait()时,当前线程释放lock,处于waiting状态,等待其他线程通过notify()同一对象。

>>>The major difference is to wait to release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.
=>主要的不同是,当等待时,wait()会释放lock或者监视器,而sleep不会释放任何lock或者监视器。
=>wait()用于线程间通讯,而sleep()用于当前线程执行暂停。

>>>wait():Causes the current thread to wait until either another thread invokes the
java.lang.Object.notify() method or the java.lang.Object.notifyAll()method for this object, or a specified amount of time has elapsed.
>>>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.
=>sleep()不会释放lock,

猜你喜欢

转载自can-do.iteye.com/blog/2250403