Difference between sleep and wait

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2022-05-26

What is the difference between wait() and sleep() in threads?

CPU usage comparison

sleep() "uses" all of its available CPU-cycles but since the thread will be in "WAITING"-state, these can be yielded if necessary - in fact most operating systems automatically yield the cycles IF it is possible, hence your thread will not create any actual CPU-load ... it will do so on older operating systems, though.

When we use the sleep() method, a thread gets started after a specified time interval, unless it is interrupted.

Use cases of wait

Interruption is intended as a mechanism to gently encourage a thread to stop running entirely and cancel remaining operations.

We can wake the thread by calling either the notify() or notifyAll() methods on the monitor that is being waited on.

Wait has the benefit of leaving your code more responsive than the nuclear "sleep" option.

wait/notify are typically used to wait for some other thread to accomplish a task, or to wait until a certain condition is satisfied.

wait(), theoretically does not use any cycles (but in practice might, e.g. if implemented in python layer)