English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Разница между Wait и Sleep в Java

Wait()-The thread releases ownership of this monitor and waits until another thread notifies the monitor of the object by callingnotify()method ornotifyAll()method wakes up the thread. Then, the thread waits until it can regain ownership of the monitor and resume execution.

Sleep()-This method puts the currently executing thread into a sleep state (temporarily stops execution) for the specified number of milliseconds. The thread does not lose any ownership of monitors. It will send the current thread to the "unrunnable" state within the specified time.

serial numberkeywaitingsleeping
1
class 
The Wait() method belongs to the Object class 
The Sleep() method belongs to the Thread class 
2
Lock release 
Wait() releases the lock on the object 
It will not release the lock on the object 
3
call context
You can call Wait() on the object itself 
You can call Sleep() on the thread 
4.
wake-up condition
until the callnotify(),notifyAll()from the object
until at least the time expires or the call is interrupted
5
False wake-up 
The program may cause a false wake-up 
It will not cause a false wake-up.

Пример SynchronizedMap

synchronized(lockedObject){
   while(condition == true){
      lockedObject.wait() //releases lockedObject lock
   {}
   Thread.sleep(100); //puts current thread on Sleep
{}
Основной учебник
Рекомендуем к просмотру