logo

Thread.sleep() em Java com exemplos

A classe Java Thread fornece as duas variantes do método sleep(). A primeira aceita apenas um argumento, enquanto a outra variante aceita dois argumentos. O método sleep() está sendo usado para interromper o funcionamento de um thread por um determinado período de tempo. O tempo até o qual o thread permanece no estado de hibernação é conhecido como tempo de hibernação do thread. Terminado o tempo de suspensão, o thread inicia sua execução de onde parou.

A sintaxe do método sleep():

A seguir está a sintaxe do método sleep().

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

O método sleep() com um parâmetro é o método nativo, e a implementação do método nativo é realizada em outra linguagem de programação. Os outros métodos com os dois parâmetros não são o método nativo. Ou seja, sua implementação é realizada em Java. Podemos acessar os métodos sleep() com a ajuda da classe Thread, pois a assinatura dos métodos sleep() contém a palavra-chave estática. O método nativo, assim como o método não nativo, lança uma exceção verificada. Portanto, o bloco try-catch ou a palavra-chave throws podem funcionar aqui.

10 de 50,00

O método Thread.sleep() pode ser usado com qualquer thread. Isso significa que qualquer outro thread ou thread principal pode invocar o método sleep().

Parâmetros:

A seguir estão os parâmetros usados ​​no método sleep().

mls: O tempo em milissegundos é representado pelo parâmetro mls. A duração pela qual o thread irá dormir é dada pelo método sleep().

n: Ele mostra o tempo adicional até o qual o programador ou desenvolvedor deseja que o thread fique no estado de suspensão. O intervalo de n é de 0 a 999999.

O método não retorna nada.

tornando o script de shell executável

Pontos importantes a serem lembrados sobre o método Sleep()

Sempre que os métodos Thread.sleep() são executados, ele sempre interrompe a execução do thread atual.

Sempre que outro thread interrompe enquanto o thread atual já está no modo de suspensão, a InterruptedException é lançada.

Se o sistema que está executando os threads estiver ocupado, o tempo real de suspensão do thread será geralmente maior em comparação com o tempo passado nos argumentos. No entanto, se o sistema que executa o método sleep() tiver menos carga, o tempo real de suspensão do thread será quase igual ao tempo passado no argumento.

gerenciador de tarefas para linux

Exemplo do método sleep() em Java: no thread personalizado

O exemplo a seguir mostra como se pode usar o método sleep() no thread personalizado.

Nome do arquivo: TestSleepMethod1.java

exemplos nfa
 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 você bem sabe, apenas um thread é executado por vez. Se você suspender um thread pelo tempo especificado, o agendador de threads selecionará outro thread e assim por diante.

Exemplo do método sleep() em Java: no thread principal

Nome do arquivo: 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;>

Exemplo do método sleep() em Java: quando o tempo de sono é -ive

O exemplo a seguir lança a exceção IllegalArguementException quando o tempo de suspensão é negativo.

Nome do arquivo: 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;>