logo

Thread.sleep() en Java con ejemplos

La clase Java Thread proporciona las dos variantes del método sleep(). La primera acepta sólo un argumento, mientras que la otra variante acepta dos argumentos. El método sleep() se utiliza para detener el funcionamiento de un hilo durante un período de tiempo determinado. El tiempo hasta el cual el hilo permanece en estado inactivo se conoce como tiempo de inactividad del hilo. Una vez finalizado el tiempo de inactividad, el hilo comienza su ejecución desde donde lo dejó.

golpe de división de cuerdas

La sintaxis del método sleep():

A continuación se muestra la sintaxis del método sleep().

 public static void sleep(long mls) throws InterruptedException public static void sleep(long mls, int n) throws InterruptedException 

El método sleep() con un parámetro es el método nativo y la implementación del método nativo se logra en otro lenguaje de programación. Los otros métodos que tienen los dos parámetros no son el método nativo. Es decir, su implementación se realiza en Java. Podemos acceder a los métodos sleep() con la ayuda de la clase Thread, ya que la firma de los métodos sleep() contiene la palabra clave estática. Tanto el método nativo como el no nativo arrojan una excepción marcada. Por lo tanto, el bloque try-catch o la palabra clave throws pueden funcionar aquí.

El método Thread.sleep() se puede utilizar con cualquier hilo. Significa que cualquier otro hilo o el hilo principal puede invocar el método sleep().

Parámetros:

Los siguientes son los parámetros utilizados en el método sleep().

mls: El tiempo en milisegundos está representado por el parámetro mls. La duración durante la cual el hilo dormirá viene dada por el método sleep().

es una relación

norte: Muestra el tiempo adicional hasta el cual el programador o desarrollador desea que el hilo esté en estado inactivo. El rango de n es de 0 a 999999.

El método no devuelve nada.

Puntos importantes para recordar sobre el método Sleep()

Cada vez que se ejecutan los métodos Thread.sleep(), siempre detiene la ejecución del hilo actual.

fecha a cadena

Cada vez que otro hilo interrumpe mientras el hilo actual ya está en modo de suspensión, se lanza la InterruptedException.

Si el sistema que ejecuta los subprocesos está ocupado, entonces el tiempo de inactividad real del subproceso generalmente es mayor en comparación con el tiempo transcurrido en los argumentos. Sin embargo, si el sistema que ejecuta el método sleep() tiene menos carga, entonces el tiempo de inactividad real del hilo es casi igual al tiempo transcurrido en el argumento.

Ejemplo del método sleep() en Java: en el hilo personalizado

El siguiente ejemplo muestra cómo se puede utilizar el método sleep() en el hilo personalizado.

Nombre del archivo: TestSleepMethod1.java

herramienta de curación gimp
 class TestSleepMethod1 extends Thread{ public void run(){ for(int i=1;i<5;i++){ 500 the thread will sleep for milli seconds try{thread.sleep(500);}catch(interruptedexception e){system.out.println(e);} system.out.println(i); } public static void main(string args[]){ testsleepmethod1 t1="new" testsleepmethod1(); t2="new" t1.start(); t2.start(); < pre> <p> <strong>Output:</strong> </p> <pre> 1 1 2 2 3 3 4 4 </pre> <p>As you know well that at a time only one thread is executed. If you sleep a thread for the specified time, the thread scheduler picks up another thread and so on.</p> <h3>Example of the sleep() Method in Java : on the main thread</h3> <p> <strong>FileName:</strong> TestSleepMethod2.java</p> <pre> // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod2 { // main method public static void main(String argvs[]) { try { for (int j = 0; j <5; 1 1000 j++) { the main thread sleeps for milliseconds, which is sec whenever loop runs thread.sleep(1000); displaying value of variable system.out.println(j); } catch (exception expn) catching exception system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 2 3 4 </pre> <h3>Example of the sleep() Method in Java: When the sleeping time is -ive</h3> <p>The following example throws the exception IllegalArguementException when the time for sleeping is negative.</p> <p> <strong>FileName:</strong> TestSleepMethod3.java</p> <pre> // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod3 { // main method public static void main(String argvs[]) { // we can also use throws keyword followed by // exception name for throwing the exception try { for (int j = 0; j <5; j++) { it throws the exception illegalargumentexception as time is -ive which -100 thread.sleep(-100); displaying variable's value system.out.println(j); } catch (exception expn) iscaught here system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> java.lang.IllegalArgumentException: timeout value is negative </pre> <hr></5;></pre></5;></pre></5;i++){>

Como bien sabes, a la vez solo se ejecuta un hilo. Si suspende un subproceso durante el tiempo especificado, el programador de subprocesos selecciona otro subproceso y así sucesivamente.

Ejemplo del método sleep() en Java: en el hilo principal

Nombre del archivo: TestSleepMethod2.java

 // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod2 { // main method public static void main(String argvs[]) { try { for (int j = 0; j <5; 1 1000 j++) { the main thread sleeps for milliseconds, which is sec whenever loop runs thread.sleep(1000); displaying value of variable system.out.println(j); } catch (exception expn) catching exception system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 2 3 4 </pre> <h3>Example of the sleep() Method in Java: When the sleeping time is -ive</h3> <p>The following example throws the exception IllegalArguementException when the time for sleeping is negative.</p> <p> <strong>FileName:</strong> TestSleepMethod3.java</p> <pre> // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod3 { // main method public static void main(String argvs[]) { // we can also use throws keyword followed by // exception name for throwing the exception try { for (int j = 0; j <5; j++) { it throws the exception illegalargumentexception as time is -ive which -100 thread.sleep(-100); displaying variable\'s value system.out.println(j); } catch (exception expn) iscaught here system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> java.lang.IllegalArgumentException: timeout value is negative </pre> <hr></5;></pre></5;>

Ejemplo del método sleep() en Java: cuando el tiempo de dormir es -ive

El siguiente ejemplo arroja la excepción IllegalArguementException cuando el tiempo para dormir es negativo.

Nombre del archivo: TestSleepMethod3.java

 // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod3 { // main method public static void main(String argvs[]) { // we can also use throws keyword followed by // exception name for throwing the exception try { for (int j = 0; j <5; j++) { it throws the exception illegalargumentexception as time is -ive which -100 thread.sleep(-100); displaying variable\'s value system.out.println(j); } catch (exception expn) iscaught here system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> java.lang.IllegalArgumentException: timeout value is negative </pre> <hr></5;>