Hilos en Java
Por ejemplo, imagine que su programa tiene un hilo principal responsable de mostrar la interfaz de usuario. Al mismo tiempo, puede crear un hilo adicional para cargar datos desde la red o realizar cálculos complejos. Esto ayuda a que el programa sea más receptivo y eficiente.
Declaración de un hilo en Java
Con la clase Thread: se puede crear una subclase de la clase Thread y sobrescribir el método run() , que contiene el código que se ejecutará en el nuevo hilo.
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();
Uso de la interfaz Runnable
Con la interfaz Runnable, es posible implementar la interfaz Runnable, proporcionar un método run() y pasarlo al constructor de la clase 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();
Herencia de la clase Thread
De manera alternativa, se puede heredar la clase Thread y sobrescribir el 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 } }
Implementación de la interfaz Runnable
También es posible implementar la interfaz Runnable y en ella definir el 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 } }
El método run() en un hilo de Java permite ejecutar código en un hilo separado, incluyendo tareas como manipulación de datos, cálculos, descarga de archivos y envío o recepción de datos a través de la red.
Diferencia entre Thread y Runnable
En Java, un Thread es un canal especial que permite la ejecución concurrente de tareas, posibilitando que el programa realice operaciones en un hilo separado, como cálculos o procesos de larga duración como la carga de datos.
La interfaz Runnable, con su único método run(), define una tarea que será ejecutada por un hilo. Se puede pasar una implementación de Runnable al constructor de un Thread para ejecutar la tarea en un nuevo hilo. Este método facilita la gestión y ejecución eficiente de tareas en paralelo.
Métodos disponibles para hilos en Java
Iniciar un hilo utilizando el método start(), lo que indica que el código debe ejecutarse en un nuevo hilo. Esto significa que el hilo principal continúa ejecutando su propio código y no espera a que el hilo recién iniciado finalice.
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()); } }
También disponemos de un método para que el hilo principal espere la ejecución del hilo que ha iniciado, utilizando el método join(). Este método espera hasta que el hilo se haya ejecutado completamente. Puede comprobar si el hilo se está ejecutando actualmente utilizando el método isAlive().
El código Thread.sleep(5000) pausa el hilo durante 5000 milisegundos (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
}
En el ejemplo, antes de llamar a join(), el hilo estaba trabajando. Después de llamar a join(), ya no lo está, porque join() significa que esperaremos en ese punto hasta que el hilo termine su ejecución.
Si queremos detener un hilo, podemos utilizar el método interrupt(). Sin embargo, para que funcione, es necesario comprobar si el hilo que estamos deteniendo está interrumpido.
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 ejemplo crea un hilo que ejecuta una tarea en un bucle hasta que es interrumpido. Cuando el hilo es interrumpido mientras está durmiendo, lanza una excepción, la maneja estableciendo la bandera de interrupción y luego termina.
Sin un manejador de la excepción InterruptedException en el hilo, el hilo no sería interrumpido.
Estos métodos permiten gestionar el ciclo de vida y la ejecución de los hilos en Java, ofreciendo flexibilidad y control sobre las aplicaciones multihilo. En los siguientes capítulos, exploraremos más sobre estos métodos.
1. ¿Qué es un hilo en Java?
2. ¿Cuál es la diferencia entre la clase Thread y la interfaz Runnable en Java?
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
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
Hilos en Java
Desliza para mostrar el menú
Por ejemplo, imagine que su programa tiene un hilo principal responsable de mostrar la interfaz de usuario. Al mismo tiempo, puede crear un hilo adicional para cargar datos desde la red o realizar cálculos complejos. Esto ayuda a que el programa sea más receptivo y eficiente.
Declaración de un hilo en Java
Con la clase Thread: se puede crear una subclase de la clase Thread y sobrescribir el método run() , que contiene el código que se ejecutará en el nuevo hilo.
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();
Uso de la interfaz Runnable
Con la interfaz Runnable, es posible implementar la interfaz Runnable, proporcionar un método run() y pasarlo al constructor de la clase 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();
Herencia de la clase Thread
De manera alternativa, se puede heredar la clase Thread y sobrescribir el 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 } }
Implementación de la interfaz Runnable
También es posible implementar la interfaz Runnable y en ella definir el 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 } }
El método run() en un hilo de Java permite ejecutar código en un hilo separado, incluyendo tareas como manipulación de datos, cálculos, descarga de archivos y envío o recepción de datos a través de la red.
Diferencia entre Thread y Runnable
En Java, un Thread es un canal especial que permite la ejecución concurrente de tareas, posibilitando que el programa realice operaciones en un hilo separado, como cálculos o procesos de larga duración como la carga de datos.
La interfaz Runnable, con su único método run(), define una tarea que será ejecutada por un hilo. Se puede pasar una implementación de Runnable al constructor de un Thread para ejecutar la tarea en un nuevo hilo. Este método facilita la gestión y ejecución eficiente de tareas en paralelo.
Métodos disponibles para hilos en Java
Iniciar un hilo utilizando el método start(), lo que indica que el código debe ejecutarse en un nuevo hilo. Esto significa que el hilo principal continúa ejecutando su propio código y no espera a que el hilo recién iniciado finalice.
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()); } }
También disponemos de un método para que el hilo principal espere la ejecución del hilo que ha iniciado, utilizando el método join(). Este método espera hasta que el hilo se haya ejecutado completamente. Puede comprobar si el hilo se está ejecutando actualmente utilizando el método isAlive().
El código Thread.sleep(5000) pausa el hilo durante 5000 milisegundos (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
}
En el ejemplo, antes de llamar a join(), el hilo estaba trabajando. Después de llamar a join(), ya no lo está, porque join() significa que esperaremos en ese punto hasta que el hilo termine su ejecución.
Si queremos detener un hilo, podemos utilizar el método interrupt(). Sin embargo, para que funcione, es necesario comprobar si el hilo que estamos deteniendo está interrumpido.
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 ejemplo crea un hilo que ejecuta una tarea en un bucle hasta que es interrumpido. Cuando el hilo es interrumpido mientras está durmiendo, lanza una excepción, la maneja estableciendo la bandera de interrupción y luego termina.
Sin un manejador de la excepción InterruptedException en el hilo, el hilo no sería interrumpido.
Estos métodos permiten gestionar el ciclo de vida y la ejecución de los hilos en Java, ofreciendo flexibilidad y control sobre las aplicaciones multihilo. En los siguientes capítulos, exploraremos más sobre estos métodos.
1. ¿Qué es un hilo en Java?
2. ¿Cuál es la diferencia entre la clase Thread y la interfaz Runnable en Java?
¡Gracias por tus comentarios!