First of all, Thread.sleep() is Blocking library method. Threads may block, or pause, for several reasons: waiting for I/O completion, waiting to acquire a lock, waiting to wake up from Thread.sleep, or waiting for the result of a computation in another thread. When a thread blocks, it is usually suspended and placed in one of the blocked thread states.
So, when you call the sleep() method, Thread leaves the CPU and stops its
execution for a period of time. During this time, it's not consuming CPU time,
so the CPU can be executing other tasks.When Thread is sleeping and is
interrupted, the method throws an InterruptedException exception immediately
and doesn't wait until the sleeping time finishes.
The Java concurrency API has another method that makes a Thread object leave the CPU. It's the yield() method, which indicates to the JVM that the Thread object can leave the CPU for other tasks. The JVM does not guarantee that it will comply with this request. Normally, it's only used for debug purposes.
One of the confusion with sleep() is that how it is different from wait() method of object class.
The major difference between wait and sleep is that wait() method release the acquired monitor when thread is waiting while Thread.sleep() method keeps the lock or monitor even if thread is waiting.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…