我需要java中的wait和sleep方法之间的确切区别。请详细说明上述方法。
答案 0 :(得分:0)
<强>睡眠():强> 它是Thread类的静态方法。它使当前线程进入&#34; Not Runnable&#34;指定时间的状态。在此期间,线程会保留已获取的锁定(监视器)。
wait():这是Object类的一个方法。它使当前线程进入&#34; Not Runnable&#34;州。在对象上调用Wait,而不是在线程上调用。在调用wait()方法之前,对象应该是同步的,意味着对象应该在synchronized块内。对wait()的调用释放获取的锁。 的例如强>
synchronized(LOCK) {
Thread.sleep(1000); // LOCK is held
}
synchronized(LOCK) {
LOCK.wait(); // LOCK is not held
}
让我们对以上各点进行分类:
致电:
wait(): Call on an object; current thread must synchronize on the lock object.
sleep(): Call on a Thread; always currently executing thread.
同步:
wait(): when synchronized multiple threads access same Object one by one.
sleep(): when synchronized multiple threads wait for sleep over of sleeping thread.
保持锁定:
wait(): release the lock for other objects to have chance to execute.
sleep(): keep lock for at least t times if timeout specified or somebody interrupt.
唤醒条件:
wait(): until call notify(), notifyAll() from object
sleep(): until at least time expire or call interrupt().
用法:
sleep(): for time-synchronization and;
wait(): for multi-thread-synchronization.