Thread Class é uma classe que é basicamente um thread de execução dos programas. Ele está presente no pacote Java.lang . A classe Thread contém o método Sleep() . Existem dois métodos sobrecarregados do método Sleep() presentes na Thread Class, um com um argumento e outro com dois argumentos. O método sleep() é usado para parar a execução do thread atual (o que quer que esteja em execução no sistema) por um período específico de tempo e, após esse período de tempo terminar, o thread que está executando antes começa a executar novamente.

Ponto importante sobre o método Thread.sleep():

  • Método Sempre que Thread.sleep() funciona para executar, ele sempre pausa a execução do thread atual.
  • Se qualquer outro encadeamento interromper quando o encadeamento está inativo, InterruptedException será lançado.
  • Se o sistema estiver ocupado, então o tempo real em que o encadeamento hibernará será mais comparado ao passado ao chamar o método de hibernação e se o sistema tiver menos carga, o tempo real de hibernação do encadeamento será próximo ao tempo passado chamando o método sleep().

Método da sintaxe do sono()

  • public static void sleep (long millis) lança InterruptedException   
  • public static void sleep (long millis) lança IllegalArguementException
  • public static void sleep (long millis, int nanos) lança InterruptedException  
  • public static void sleep (long millis, int nanos) lança IllegalArguementException

Parâmetros passados ​​no método Thread.Sleep()

  • milissegundos: duração de tempo em milissegundos durante o qual o encadeamento ficará suspenso
  • nanos: este é o tempo adicional em nanossegundos durante o qual desejamos que o encadeamento entre em suspensão. Ele varia de 0 a 999999. 

Retorno tipo de sono() Método: Ele não retorna qualquer valor, a isto é o tipo de retorno da função do sono é nula.

O método sleep com um parâmetro é um método nativo, ou seja, a implementação deste método é feita em outra linguagem de programação e o outro método com dois parâmetros não é um método nativo, ou seja, sua implementação é feita em Java. Ambos os métodos de suspensão são estáticos, ou seja, podemos acessá-los usando a classe Thread. Ambos os métodos lançam uma exceção verificada, ou seja, podemos tratar a exceção usando a palavra-chave throws ou usando o bloco try e catch. 

Podemos usar o método Thread.Sleep() para qualquer thread, ou seja, podemos usá-lo com o thread principal ou qualquer outro thread que fizermos programaticamente.

  • Usando o método Thread.Sleep() para o thread principal 
// 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 foloowed 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);
        }
    }
}
Saída
0
1
2
3
4
  • Usando o método Thread.Sleep() para thread personalizado 
// 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 foloowed 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();
    }
}
Saída
0
1
2
3
4
  •  IllegalArguementException When Sleep Time Is Negative
// 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 foloowed 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);
        }
    }
}
Saída
java.lang.IllegalArgumentException: o valor de tempo limite é negativo