Java — Java.lang.Thread.sleep() Method | Code Factory

Index Page : Link

Donate : Link

WordPress Blog : Link

  • If a thread don’t want to perform any operation for a particular amount of time then we should go for sleep() method.
  • Every sleep() method throws , which is checked exception, Hence whenever we are using sleep() method compulsary we should handle either by try catch or throws keyword otherwise we will get CE error.

Output :

How a thread can interrupt another thread :

  • A thread can interrupt a sleeping thread or waiting thread by using interrupt() method of thread class.

Output :

  • If we comment line #1 then main thread wouldn’t interrupt child thread. In this case child thread will execute 5 times.
  • If we are not commenting line #1 then main thread interrupt child thread.
  • * Whenever we are calling intrrupt() method, If the target thread not in sleeping state or waiting state then there is no any intrrupt() call immediately. Interrupt call will waited until target thread entered into sleeping or waiting state. If the target thread entered into sleeping or waiting state then immediately intrrupt call will interrupt target thread.
  • * If the target thread never entered into sleeping or waiting state in it’s lifetime then there is no impact of intrrupt call. This is the only case where intrrupt call will be wasted.

Output :

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store