Sleep():该方法用于将当前线程的执行暂停指定的时间(以毫秒为单位)。在这里,线程不会失去它对监视器的所有权并恢复它的执行
Wait():这个方法在对象类中定义。它告诉调用线程(又名当前线程)等待另一个线程为此对象调用 notify() 或 notifyAll() 方法,线程等待直到它重新获得监视器的所有权和恢复执行。
Wait() | Sleep() |
---|---|
Wait() method belongs to Object class. | Sleep() method belongs to Thread class. |
Wait() method releases lock during Synchronization. | Sleep() method does not release the lock on object during Synchronization. |
Wait() should be called only from Synchronized context. | There is no need to call sleep() from Synchronized context. |
Wait() is not a static method. | Sleep() is a static method. |
Wait() Has Three Overloaded Methods:
|
Sleep() Has Two Overloaded Methods:
|
public final void wait(long timeout) | public static void sleep(long millis) throws Interrupted_Execption |
睡眠方法示例:
synchronized(monitor)
{
Thread.sleep(1000); Here Lock Is Held By The Current Thread
//after 1000 milliseconds, current thread will wake up, or after we call that is interrupt() method
}
示例等待方法:
synchronized(monitor)
{
monitor.wait() Here Lock Is Released By Current Thread
}
wait() 和 sleep() 方法的相似之处:
- 两者都使当前线程进入不可运行状态。
- 两者都是本机方法。
下面是调用wait()和sleep()方法的代码片段:
Java
synchronized(monitor){
while(condition == true)
{
monitor.wait() //releases monitor lock
}
Thread.sleep(100); //puts current thread on Sleep
}
Java
// Java program to demonstrate the difference
// between wait and sleep
class GfG{
private static Object LOCK = new Object();
public static void main(String[] args)
throws InterruptedException {
Thread.sleep(1000);
System.out.println("Thread '" + Thread.currentThread().getName() +
"' is woken after sleeping for 1 second");
synchronized (LOCK)
{
LOCK.wait(1000);
System.out.println("Object '" + LOCK + "' is woken after" +
" waiting for 1 second");
}
}
}
程序:
Java
// Java program to demonstrate the difference
// between wait and sleep
class GfG{
private static Object LOCK = new Object();
public static void main(String[] args)
throws InterruptedException {
Thread.sleep(1000);
System.out.println("Thread '" + Thread.currentThread().getName() +
"' is woken after sleeping for 1 second");
synchronized (LOCK)
{
LOCK.wait(1000);
System.out.println("Object '" + LOCK + "' is woken after" +
" waiting for 1 second");
}
}
}
输出
Thread 'main' is woken after sleeping for 1 second
Object 'java.lang.Object@1d81eb93' is woken after waiting for 1 second