Método Thread.sleep() en Java con ejemplos

Thread Class es una clase que es básicamente un hilo de ejecución de los programas. Está presente en el paquete Java.lang . La clase Thread contiene el método Sleep() . Hay dos métodos sobrecargados del método Sleep() presentes en Thread Class, uno con un argumento y otro con dos argumentos. El método sleep() se utiliza para detener la ejecución del subproceso actual (cualquiera que se esté ejecutando en el sistema) durante un tiempo específico y, una vez que finaliza ese tiempo, el subproceso que se está ejecutando anteriormente comienza a ejecutarse nuevamente.

Punto importante sobre el método Thread.sleep():

Java

// Java Program for sleeping the main thread.
 
import java.io.*;
import java.lang.Thread;
 
class GFG {
    public static void main(String[] args)
    {
        // we can also use throws keyword followed by
        // exception name for throwing the exception
       
        try {
            for (int i = 0; i < 5; i++) {
               
                // it will sleep the main thread for 1 sec
                // ,each time the for loop runs
                Thread.sleep(1000);
               
                // printing the value of the variable
                System.out.println(i);
            }
        }
        catch (Exception e) {
           
            // catching the exception
            System.out.println(e);
        }
    }
}

Java

// Java Program for sleeping the custom thread.
 
import java.io.*;
import java.lang.Thread;
 
class GFG extends Thread {
 
    public void run()
    {
        // thread 0
 
        // we can also use throws keyword followed by
        // exception name for throwing the exception
        try {
            for (int i = 0; i < 5; i++) {
               
                // it will sleep the main thread for 1 sec
                // ,each time the for loop runs
                Thread.sleep(1000);
               
                // This Thread.sleep() method will sleep the
                // thread 0.
                // printing the value of the variable
                System.out.println(i);
            }
        }
        catch (Exception e) {
           
            // catching the exception
            System.out.println(e);
        }
    }
    public static void main(String[] args)
    {
        // main thread
        GFG obj = new GFG();
        obj.start();
    }
}

Java

// Java Program for showing how exception can occur if we
// pass the negative timeout value.
 
import java.io.*;
import java.lang.Thread;
 
class GFG {
    public static void main(String[] args)
    {
        // we can also use throws keyword followed by
        // exception name for throwing the exception
       
        try {
            for (int i = 0; i < 5; i++) {
               
                // this will throw the
                // IllegalArgumentException
                Thread.sleep(-100);
               
                // printing the value of the variable
                System.out.println(i);
            }
        }
        catch (Exception e) {
           
            // catching the exception
            System.out.println(e);
        }
    }
}

Publicación traducida automáticamente

Artículo escrito por lavishgarg26 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *