Sleep() method in threads in java - 10 key features with programs


Contents of page :
  • sleep()
  • 10 salient features of sleep() method >
  • Using sleep() method in main thread >
  • Using sleep() method in thread invoked by main thread >
  • Above we read that sleep() is a static method, let’s understand it by program>

sleep() is a native method, its implementation is provided by JVM.



10 salient features of sleep() method >

  • Definition : sleep() methods causes current thread to sleep for specified number of milliseconds (i.e. time passed in sleep method as parameter). Ex- Thread.sleep(10) causes currently executing thread to sleep for 10 millisec.

  • Thread state : when sleep() is called on thread it goes from running to waiting state and can return to runnable state when sleep time is up.

  • Exception : sleep() method throws compile time exception i.e. InterruptedException.

  • Waiting time : sleep() method have got few options.
    1. sleep(long millis) - Causes the currently executing thread to sleep for the specified number of milliseconds
public static native void sleep(long millis) throws InterruptedException;

    1. sleep(long millis, int nanos) - Causes the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.
public static native void sleep(long millis,int nanos) throws InterruptedException;


  • static method : sleep() is a static method, causes the currently executing thread to sleep for the specified number of milliseconds.

  • Native method : implementation of sleep() method is provided by JVM.
Let’s see definition of yield() method as given in java.lang.Thread -
public static native void sleep(long millis) throws InterruptedException;


  • Belongs to which class : sleep() method belongs to java.lang.Thread class.

  • synchronized block : thread need not to to acquire object lock before calling sleep() method i.e. sleep() method can be called from outside synchronized block.


Using sleep() method in main thread >
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class SleepMain {
   public static void main(String...args) throws InterruptedException{
          System.out.println(Thread.currentThread().getName() + " has started");
          Thread.sleep(2000);
          System.out.println(Thread.currentThread().getName() + " has ended");
   }
}
/*OUTPUT
main has started
main has ended
*/
In the above program, main thread starts than it call sleep(2000) method and it enters waiting state for 2000 millisec (2 seconds).  Once 2 seconds are over main thread comes into running state and finish its execution.


Using sleep() method in thread invoked by main thread >
class MyRunnable implements Runnable {
   public void run() {
          System.out.println(Thread.currentThread().getName() + " has started");
          try {
                 Thread.sleep(2000);
          } catch (InterruptedException e) {
                 e.printStackTrace();
          }
          System.out.println(Thread.currentThread().getName() + " has ended");
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class SleepRunnable {
   public static void main(String... args) {
          System.out.println(Thread.currentThread().getName() + " has started");
          Thread thread1 = new Thread(new MyRunnable(), "Thread-1");
          thread1.start();
          System.out.println(Thread.currentThread().getName() + " has ended");
   }
}
/*OUTPUT
main has started
main has ended
Thread-1 has started
Thread-1 has ended

*/
In the above program, main thread starts invokes Thread-1 and Thread-1 calls sleep method and it enters waiting state for 2000 millisec, meanwhile main thread gets chance to execute and finish. Once 2 seconds are over Thread-1 comes into running state and finish its execution.


Above we read that sleep() is a static method, let’s understand it by program>
  • static method : sleep() is a static method, causes the currently executing thread to sleep for the specified number of milliseconds.

In the below program first main thread started, than it invoked Thread-1, then Thread-1 called sleep(100) method to ensure that main thread don’t complete before Thread-1, than execution control went to  main thread  and it called thread1.sleep(10000) but rather than putting Thread-1 on sleep it made main thread to sleep. And Thread-1 ended before main thread.
class MyRunnable implements Runnable {
   public void run() {
          System.out.println(Thread.currentThread().getName() + " has started");
          try {
                 Thread.sleep(100); //ensure that main thread don’t complete before Thread-1
          } catch (InterruptedException e) {
                 e.printStackTrace();
          }
          System.out.println(Thread.currentThread().getName() + " has ended");
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class SleepStatic {
   public static void main(String... args) throws InterruptedException {
          System.out.println(Thread.currentThread().getName() + " has started");
          Thread thread1 = new Thread(new MyRunnable(), "Thread-1");
          thread1.start();
          thread1.sleep(10000); //we will face warning - The static method
                    //sleep(long) from the type Thread should be accessed in a static way
          System.out.println(Thread.currentThread().getName() + " has ended");
   }
}
/*OUTPUT
main has started
Thread-1 has started
Thread-1 has ended
main has ended
*/




RELATED LINKS>


run() and Start() methods >

What will happen if we don’t override run method of thread?

What will happen if we override start method of thread?

Difference between starting thread with run() and start() methods in java

Can we start Thread again?


Important Thread methods (salient features, usage with programs)>

Join() method - ensure all threads that started from main must end in order in which they started and also main should end in last. Types of join() method-10 salient features of join

Sleep() method in threads - 10 key features with programs

Yield() method in threads - 8 key features with programs

Wait() and notify() methods- Definition, 8 key features, solving consumer producer problem with & without these methods and consequences of not using wait() and notify() methods.

Daemon threads - 12 salient features of Daemon Thread

2 alternate ways to stop thread, as stop() method is deprecated

Using Suspend and resume method in threads



Differences between important thread methods >

Difference between wait() and sleep() method in threads

Differences and similarities between yield() and sleep() in threads

Difference between notify() and notifyAll() methods, with program

Difference between wait() and wait(long timeout) -What will be Thread states



Interviews >


THREADS - Top 80 interview questions and answers, important interview OUTPUT questions and answers, Set-2 > Q61- Q80






No comments:

Post a Comment