What is the difference between wait() and sleep() methods?

The wait() and sleep() methods are both used to pause thread execution, but they serve different purposes. The wait() method is used for inter-thread communication and causes the current thread to release the object's monitor lock and enter a waiting state until another thread notifies it. In contrast, sleep() simply pauses the current thread for a specified period without releasing any locks it holds.

Key Points: • wait() is defined in the Object class, whereas sleep() is defined in the Thread class. • wait() releases the monitor lock, allowing other threads to acquire it; sleep() keeps all acquired locks during the pause. • wait() requires synchronization and is typically used with notify() or notifyAll(), while sleep() is mainly used for introducing delays.

Example: Imagine two employees sharing a meeting room. If one employee uses wait(), they leave the room and allow others to use it until they are called back. If they use sleep(), they stay inside the room while resting, preventing others from entering.

Code Example:

class SharedResource {

    public synchronized void waitExample() throws InterruptedException {
        System.out.println("Thread entering wait state");
        wait();
        System.out.println("Thread resumed");
    }
}

public class Main {

    public static void main(String[] args) throws InterruptedException {

        Thread.sleep(1000);

        System.out.println("Main thread resumed after 1 second");
    }
}

Interview Tip: A concise interview answer is: wait() releases the object's monitor lock and waits until notified by another thread, making it suitable for thread coordination. sleep() pauses execution for a specified time without releasing any locks and is mainly used to introduce delays.