Câu hỏi phỏng vấn Java
Câu hỏi

Compare the sleep() and wait() methods in Java

Câu trả lời

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:

  • Class Belonging: sleep() is a static method of the Thread class.
  • Purpose: It is used to pause the execution of the current thread for a specified duration of time.
  • Lock Behavior: When a thread is put to sleep, it holds any locks it has – it does not release any object locks.
  • Usage Context: sleep() can be called from any context and is not dependent on the object's monitor.
  • Method Signature: sleep() has two overloaded versions: sleep(long millis) and sleep(long millis, int nanos), both of which can throw InterruptedException.
  • Interruption: If another thread interrupts the sleeping thread, it throws an InterruptedException.
  • Static Method: Being a static method, sleep() always affects the current executing thread, regardless of which thread object calls it.

wait() Method:

  • Class Belonging: wait() is a non-static method and is part of the Object class.
  • Purpose: It causes the current thread to wait until another thread invokes notify() or notifyAll() on the same object or until the optional timeout expires.
  • Lock Behavior: When wait() is invoked, the calling thread releases the lock on the object to allow other threads to synchronize on that object.
  • Usage Context: wait() must be called from a synchronized context – the calling thread must own the object's monitor.
  • Method Signature: wait() has three versions: wait(), wait(long timeout), and wait(long timeout, int nanos), all of which can throw InterruptedException.
  • Interruption: A thread in wait() state can be woken up before the notify call or timeout by an InterruptedException.
  • Object Lock: wait() is always about the object lock; when a thread calls wait(), it sets itself in a wait state on that object's monitor.

Key Differences:

  • Lock Release: wait() releases the monitor lock, sleep() does not.
  • Class Membership: wait() is in Object class, sleep() is ...
middle

middle

Gợi ý câu hỏi phỏng vấn

senior

What is the difference between Serial and Throughput Garbage collector?

junior

What are Expressions?

middle

What is the difference between final , finalize and finally in java?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào