sleep() in Java

If a Thread did not want to perform any operation for some time then we can use sleep() and prevent the execution of that Thread.

sleep() method throws InterruptedException which is checked exception, hence when ever we are using sleep() method, we should handle InterruptedException either by try – catch block or by throws keyword otherwise we will get compilr time error

public class SleepMethod {
    public static void main(String[] args) throws InterruptedException {
        for(int i=0;i<10;i++){
            System.out.println(i);
            Thread.sleep(1000);
        }
    }
}

How a Thread Can Interrupt Another Thread?

A thread can interrupt a sleeping thread or waiting thread by using the interrupt method of the Thread class.

import com.sun.source.tree.CatchTree;

public class InterruptMethod extends Thread {
    @Override
    public void run() {
        try{
            for(int i=0;i<5;i++){
                System.out.println("Child Thread");
                Thread.sleep(10000);
            }
        }
        catch (InterruptedException e){
            System.out.println("Thread Interrupted");
        }}}
      class TheCodeDataRun{
          public static void main(String[] args) {
              InterruptMethod obj = new InterruptMethod();
              obj.start();
              obj.interrupt();
              System.out.println("Main Thread ended");
    }
}
How a Thread Can Interrupt Another Thread?

When an interrupt method is called if the target thread is not sleeping or waiting for state, then there is no immediate impact of the interrupted method call. Interrupt calls will be on the wait list until the target thread enters a sleep or waiting state. If the targeted Thread entered into a waiting state or sleep state after that interrupt call will interrupt the target Thread immediately.

Similar Java Tutorials

Leave a Comment