提供有关 Java 中等待和睡眠的详细信息。
提供有关 Java 中等待和睡眠的详细信息。
这个问题已经有了答案:
我需要准确了解Java中wait和sleep方法的区别。请详细描述以上方法的清晰细节。
admin 更改状态以发布 2023年5月24日
sleep():它是Thread类的静态方法。它使当前线程处于特定时间的“不可运行”状态。在此期间,线程保持已获取的锁(监视器)。
wait():它是Object类的方法。它使当前线程处于“不可运行”状态。wait在对象上调用,而不是线程。在调用wait()方法之前,对象应该同步,意味着对象应该在同步块中。调用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.