Java Thread Sleep

Previous
Next

Sleep method of java.lang.Thread is used to pause current execution of thread for specific period of time.

Some important points about sleep method are :

  • It causes current executing thread to sleep for specific amount of time.
  • Its accuracy depends on system timers and schedulers.
  • It keeps the monitors it has acquired, so if it is called from synchronized context, no other thread can enter that block or method.
  • If we call interrupt() method , it will wake up the sleeping thread.

Example: Create a class FirstThread.java as below.

Create main class named ThreadSleepExampleMain.java

When you run above program, you will get following output.

Thread is running
Time difference between before and after sleep call: 1001

You can see there is a delay of 1000 milliseconds (1 sec). As mentioned earlier, its accuracy depends on system timers and schedulers.

How Thread Sleep Works

Thread.sleep() works with thread scheduler to pause current thread execution for specific period of time. Once thread wait period is over, the thread’s state is changed to runnable again and it is available for further execution for CPU.

That’s all about Java Thread Sleep Example

Previous
Next

Add Comment