Provide the details about wait and sleep in java
This question already has an answer here:
sleep(): It is a static method on Thread class. It makes the current thread into the "Not Runnable" state for specified amount of time. During this time, the thread keeps the lock (monitors) it has acquired.
wait(): It is a method on Object class. It makes the current thread into the "Not Runnable" state. Wait is called on a object, not a thread. Before calling wait() method, the object should be synchronized, means the object should be inside synchronized block. The call to wait() releases the acquired lock. Eg:
synchronized(LOCK) {
Thread.sleep(1000); // LOCK is held
}
synchronized(LOCK) {
LOCK.wait(); // LOCK is not held
}
Let categorize all above points :
Call on:
wait(): Call on an object; current thread must synchronize on the lock object.
sleep(): Call on a Thread; always currently executing thread.
Synchronized:
wait(): when synchronized multiple threads access same Object one by one.
sleep(): when synchronized multiple threads wait for sleep over of sleeping thread.
Hold lock:
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.
Wake-up condition:
wait(): until call notify(), notifyAll() from object
sleep(): until at least time expire or call interrupt().
Usage:
sleep(): for time-synchronization and;
wait(): for multi-thread-synchronization.
链接地址: http://www.djcxy.com/p/92142.html
上一篇: 使用Thread.sleep(x)或wait()时我会得到异常
下一篇: 在java中提供关于等待和睡眠的详细信息