Java Concurrency – sleep() method

JavaObject Oriented ProgrammingProgramming

The sleep function

This sleep function is used to ensure that the currently executing thread goes to sleep for a specific amount of milliseconds which is passed as a parameter to the function. The thread stops executing for that number of milliseconds.

Let us see an example

Example

 Live Demo

import java.lang.*;
public class Demo implements Runnable{
   Thread my_t;
   public void run(){
      for (int i = 0; i < 3; i++){
         System.out.println(Thread.currentThread().getName()+ " " + i);
         try{
            Thread.sleep(100);
         }
         catch (Exception e){
            System.out.println(e);
         }
      }
   }
   public static void main(String[] args) throws Exception{
      Thread my_t = new Thread(new Demo());
      my_t.start();
      Thread my_t2 = new Thread(new Demo());
      my_t2.start();
   }
}

Output

Thread-0 0
Thread-1 0
Thread-0 1
Thread-1 1
Thread-0 2
Thread-1 2

A class named Demo implements the Runnable class. A new thread is defined. Next, a ‘run’ function is defined that iterates over a set of elements and gets the name of the thread using the ‘getName’ function. In the try block, the sleep function is called on the thread and the catch block prints the exception, if any occurs.

The main function creates two new instances of the Thread and it is begun using the ‘start’ function. Here also, elements are iterated over and the yield function is called on the thread.

raja
Published on 04-Jul-2020 09:00:34
Advertisements