Threads em Java
Por exemplo, imagine que seu programa possui uma thread principal responsável por exibir a interface do usuário. Ao mesmo tempo, é possível criar uma thread adicional para carregar dados da rede ou realizar cálculos complexos. Isso contribui para tornar o programa mais responsivo e eficiente.
Declarando uma Thread em Java
Com a classe Thread, é possível criar uma subclasse da classe Thread e sobrescrever o método run() , que contém o código a ser executado na nova thread.
Main.java
123456789// Create a new thread using an anonymous subclass of `Thread` Thread thread = new Thread() { public void run() { // Code that will execute in the new thread } }; // Start the thread execution thread.start();
Utilizando a Interface Runnable
Com a Runnable interface, é possível implementar a interface Runnable, fornecer um método run() e passá-lo para o construtor da classe Thread.
Main.java
123456789101112// Create a new `Runnable` instance with an anonymous class implementing the run method Runnable runnable = new Runnable() { public void run() { // Code that will execute in the new thread } }; // Create a new `Thread` instance, passing the `Runnable` as argument Thread thread = new Thread(runnable); // Start the thread execution thread.start();
Herança da Classe Thread
Como alternativa, é possível herdar a classe Thread e sobrescrever o método run().
Main.java
123456789// The `MyThread` class extends the `Thread` class to create a custom thread public class MyThread extends Thread { // The run method is overridden to define the task that the thread will execute @Override public void run() { // Code to be executed by the thread should go here } }
Implementação da Interface Runnable
Também é possível implementar a interface Runnable e nela implementar o método run():
Main.java
123456789// The `MyThread` class implements the `Runnable` interface to create a custom task public class MyThread implements Runnable { // The run method is overridden to define the task that will be executed when the thread runs @Override public void run() { // Code to be executed by the thread should go here } }
O método run() em uma thread Java permite executar código em uma thread separada, incluindo tarefas como manipulação de dados, cálculos, download de arquivos e envio ou recebimento de dados pela rede.
Diferença entre Thread e Runnable
Em Java, uma Thread é um canal especial que permite a execução concorrente de tarefas, possibilitando que seu programa realize operações em uma thread separada, como cálculos ou processos de longa duração como carregamento de dados.
A interface Runnable, com seu único método run(), define uma tarefa a ser executada por uma thread. É possível passar uma implementação de Runnable para o construtor de uma Thread para executar a tarefa em uma nova thread. Esse método auxilia no gerenciamento e execução eficiente de tarefas paralelas.
Métodos Disponíveis para Threads em Java
Início de uma thread utilizando o método start(), que indica que o código deve ser executado em uma nova thread. Isso significa que a thread principal continua executando seu próprio código e não espera a conclusão da thread recém-iniciada.
Main.java
1234567891011121314151617181920212223242526package com.example; public class Main { public static void main(String[] args) throws InterruptedException { // Create a new thread that will sleep for 5 seconds Thread thread = new Thread(() -> { try { Thread.sleep(5000); // Simulate work by sleeping for 5 seconds } catch (InterruptedException e) { throw new RuntimeException(e); // Handle interruption by rethrowing as a runtime exception } }); // Start the thread thread.start(); // Check if the thread is alive before calling `join()` System.out.println("Is the thread alive before the join() method: " + thread.isAlive()); // Wait for the thread to finish execution thread.join(); // Check if the thread is alive after `join()` System.out.println("Is the thread alive after join(): " + thread.isAlive()); } }
Também existe um método para a thread principal aguardar a execução da thread que ela iniciou, utilizando o método join(). Este método aguarda até que a thread seja totalmente executada. É possível verificar se a thread está em execução no momento utilizando o método isAlive().
O código Thread.sleep(5000) pausa a thread por 5000 milissegundos (5 segundos).
try {
Thread.sleep(5000); // Simulate work by sleeping for 5 seconds
} catch (InterruptedException e) {
throw new RuntimeException(e); // Handle interruption by rethrowing as a runtime exception
}
No exemplo, antes de chamar join(), a thread estava em execução. Após chamar join(), ela não está mais, pois join() significa que iremos aguardar naquele ponto até que a thread finalize sua execução.
Se for necessário parar uma thread, pode-se utilizar o método interrupt(). No entanto, para que funcione, é preciso verificar se a thread que está sendo parada foi interrompida.
Main.java
123456789101112131415161718192021222324252627282930313233package com.example; public class Main { public static void main(String[] args) throws InterruptedException { // Create a thread that will perform some task Thread thread = new Thread(() -> { // Loop runs until the thread is interrupted while (!Thread.currentThread().isInterrupted()) { System.out.println("Thread is running..."); // Simulate some work with a delay try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Thread was interrupted during sleep."); // Re-interrupt the thread to ensure the loop exits Thread.currentThread().interrupt(); } } System.out.println("Thread is exiting..."); }); // Start the thread thread.start(); // Let the thread run for a bit Thread.sleep(3000); // Interrupt the thread thread.interrupt(); } }
Este exemplo cria uma thread que executa uma tarefa em um loop até ser interrompida. Quando a thread é interrompida enquanto está dormindo, ela lança uma exceção, trata essa exceção definindo o sinalizador de interrupção e então termina.
Sem um manipulador de exceção InterruptedException na thread, a thread não seria interrompida.
Esses métodos permitem gerenciar o ciclo de vida e a execução das threads em Java, oferecendo flexibilidade e controle sobre aplicações multithread. Nos próximos capítulos, exploraremos mais sobre esses métodos.
1. O que é uma thread em Java?
2. Qual é a diferença entre a classe Thread e a interface Runnable em Java?
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Can you explain the difference between extending the Thread class and implementing the Runnable interface?
How does the start() method work in Java threads?
What happens if I call the run() method directly instead of start()?
Awesome!
Completion rate improved to 3.33
Threads em Java
Deslize para mostrar o menu
Por exemplo, imagine que seu programa possui uma thread principal responsável por exibir a interface do usuário. Ao mesmo tempo, é possível criar uma thread adicional para carregar dados da rede ou realizar cálculos complexos. Isso contribui para tornar o programa mais responsivo e eficiente.
Declarando uma Thread em Java
Com a classe Thread, é possível criar uma subclasse da classe Thread e sobrescrever o método run() , que contém o código a ser executado na nova thread.
Main.java
123456789// Create a new thread using an anonymous subclass of `Thread` Thread thread = new Thread() { public void run() { // Code that will execute in the new thread } }; // Start the thread execution thread.start();
Utilizando a Interface Runnable
Com a Runnable interface, é possível implementar a interface Runnable, fornecer um método run() e passá-lo para o construtor da classe Thread.
Main.java
123456789101112// Create a new `Runnable` instance with an anonymous class implementing the run method Runnable runnable = new Runnable() { public void run() { // Code that will execute in the new thread } }; // Create a new `Thread` instance, passing the `Runnable` as argument Thread thread = new Thread(runnable); // Start the thread execution thread.start();
Herança da Classe Thread
Como alternativa, é possível herdar a classe Thread e sobrescrever o método run().
Main.java
123456789// The `MyThread` class extends the `Thread` class to create a custom thread public class MyThread extends Thread { // The run method is overridden to define the task that the thread will execute @Override public void run() { // Code to be executed by the thread should go here } }
Implementação da Interface Runnable
Também é possível implementar a interface Runnable e nela implementar o método run():
Main.java
123456789// The `MyThread` class implements the `Runnable` interface to create a custom task public class MyThread implements Runnable { // The run method is overridden to define the task that will be executed when the thread runs @Override public void run() { // Code to be executed by the thread should go here } }
O método run() em uma thread Java permite executar código em uma thread separada, incluindo tarefas como manipulação de dados, cálculos, download de arquivos e envio ou recebimento de dados pela rede.
Diferença entre Thread e Runnable
Em Java, uma Thread é um canal especial que permite a execução concorrente de tarefas, possibilitando que seu programa realize operações em uma thread separada, como cálculos ou processos de longa duração como carregamento de dados.
A interface Runnable, com seu único método run(), define uma tarefa a ser executada por uma thread. É possível passar uma implementação de Runnable para o construtor de uma Thread para executar a tarefa em uma nova thread. Esse método auxilia no gerenciamento e execução eficiente de tarefas paralelas.
Métodos Disponíveis para Threads em Java
Início de uma thread utilizando o método start(), que indica que o código deve ser executado em uma nova thread. Isso significa que a thread principal continua executando seu próprio código e não espera a conclusão da thread recém-iniciada.
Main.java
1234567891011121314151617181920212223242526package com.example; public class Main { public static void main(String[] args) throws InterruptedException { // Create a new thread that will sleep for 5 seconds Thread thread = new Thread(() -> { try { Thread.sleep(5000); // Simulate work by sleeping for 5 seconds } catch (InterruptedException e) { throw new RuntimeException(e); // Handle interruption by rethrowing as a runtime exception } }); // Start the thread thread.start(); // Check if the thread is alive before calling `join()` System.out.println("Is the thread alive before the join() method: " + thread.isAlive()); // Wait for the thread to finish execution thread.join(); // Check if the thread is alive after `join()` System.out.println("Is the thread alive after join(): " + thread.isAlive()); } }
Também existe um método para a thread principal aguardar a execução da thread que ela iniciou, utilizando o método join(). Este método aguarda até que a thread seja totalmente executada. É possível verificar se a thread está em execução no momento utilizando o método isAlive().
O código Thread.sleep(5000) pausa a thread por 5000 milissegundos (5 segundos).
try {
Thread.sleep(5000); // Simulate work by sleeping for 5 seconds
} catch (InterruptedException e) {
throw new RuntimeException(e); // Handle interruption by rethrowing as a runtime exception
}
No exemplo, antes de chamar join(), a thread estava em execução. Após chamar join(), ela não está mais, pois join() significa que iremos aguardar naquele ponto até que a thread finalize sua execução.
Se for necessário parar uma thread, pode-se utilizar o método interrupt(). No entanto, para que funcione, é preciso verificar se a thread que está sendo parada foi interrompida.
Main.java
123456789101112131415161718192021222324252627282930313233package com.example; public class Main { public static void main(String[] args) throws InterruptedException { // Create a thread that will perform some task Thread thread = new Thread(() -> { // Loop runs until the thread is interrupted while (!Thread.currentThread().isInterrupted()) { System.out.println("Thread is running..."); // Simulate some work with a delay try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Thread was interrupted during sleep."); // Re-interrupt the thread to ensure the loop exits Thread.currentThread().interrupt(); } } System.out.println("Thread is exiting..."); }); // Start the thread thread.start(); // Let the thread run for a bit Thread.sleep(3000); // Interrupt the thread thread.interrupt(); } }
Este exemplo cria uma thread que executa uma tarefa em um loop até ser interrompida. Quando a thread é interrompida enquanto está dormindo, ela lança uma exceção, trata essa exceção definindo o sinalizador de interrupção e então termina.
Sem um manipulador de exceção InterruptedException na thread, a thread não seria interrompida.
Esses métodos permitem gerenciar o ciclo de vida e a execução das threads em Java, oferecendo flexibilidade e controle sobre aplicações multithread. Nos próximos capítulos, exploraremos mais sobre esses métodos.
1. O que é uma thread em Java?
2. Qual é a diferença entre a classe Thread e a interface Runnable em Java?
Obrigado pelo seu feedback!