Compare the sleep() and wait() methods in Java
Compare the sleep() and wait() methods in Java
In Java, both sleep()
and wait()
methods are used to pause the execution of a thread, but they serve different purposes and are used in different contexts.
sleep()
Method:sleep()
is a static method of the Thread
class.sleep()
can be called from any context and is not dependent on the object's monitor.sleep()
has two overloaded versions: sleep(long millis)
and sleep(long millis, int nanos)
, both of which can throw InterruptedException
.InterruptedException
.sleep()
always affects the current executing thread, regardless of which thread object calls it.wait()
Method:wait()
is a non-static method and is part of the Object
class.notify()
or notifyAll()
on the same object or until the optional timeout expires.wait()
is invoked, the calling thread releases the lock on the object to allow other threads to synchronize on that object.wait()
must be called from a synchronized context – the calling thread must own the object's monitor.wait()
has three versions: wait()
, wait(long timeout)
, and wait(long timeout, int nanos)
, all of which can throw InterruptedException
.wait()
state can be woken up before the notify call or timeout by an InterruptedException
.wait()
is always about the object lock; when a thread calls wait()
, it sets itself in a wait state on that object's monitor.wait()
releases the monitor lock, sleep()
does not.wait()
is in Object
class, sleep()
is ...middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào