Contenido del Curso
Multithreading in Java
Multithreading in Java
Threads in Java
For example, imagine your program has a main thread responsible for displaying the user interface. At the same time, you can create an additional thread to load data from the network or perform complex calculations. This helps make the program more responsive and efficient.
How can you declare a thread in Java
Using the Thread class
With the Thread
: class, you can create a subclass of the Thread
class and override the run()
method, which contains the code that will be executed in the new thread.
Main
// 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();
Using the Runnable interface
With the Runnable
interface, you can implement the Runnable
interface, provide a run()
method, and pass it to the Thread
class constructor.
Main
// 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();
Thread class inheritance
Alternatively, you can inherit the Thread
class and override the run()
method.
Main
// 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 } }
Implementation of the Runnable interface
You can also implement the Runnable
interface and in it implement the run()
method:
Main
// 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 } }
Note
The
run()
method in a Java thread lets you execute code in a separate thread, including tasks like working with data, calculations, downloading files, and sending or receiving data over the network.
What is the difference between Thread and Runnable?
In Java, a Thread
is a special channel that allows concurrent execution of tasks, enabling your program to perform operations in a separate thread, such as computations or long-running processes like data loading.
The Runnable
interface, with its single run()
method, defines a task to be executed by a thread. You can pass a Runnable
implementation to a Thread
constructor to run the task in a new thread. This method helps in managing and executing parallel tasks efficiently.
What methods exist for threads in Java?
Let's start a thread using the start()
method, which indicates that the code should run in a new thread. This means the main thread continues executing its own code and does not wait for the newly started thread to complete.
Main
package 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()); } }
We also have a method for the main thread to wait for the execution of the thread it started using the join()
method. This method waits until the thread is fully executed. You can check if the thread is currently running by using the isAlive()
method.
The code Thread.sleep(5000)
pauses the thread for 5000 milliseconds (5 seconds).
In the example, before calling join()
, the thread was working. After calling join()
, it is not, because join()
means we will wait at that point until the thread finishes its execution.
If we want to stop a thread, we can use the interrupt()
method. However, for it to work, we need to check if the thread we are stopping is interrupted.
Main
package 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(); } }
This example creates a thread that runs a task in a loop until it is interrupted. When the thread is interrupted while sleeping, it throws an exception, handles it by setting the interrupt flag, and then terminates.
Without an InterruptedException
exception handler in the thread, the thread would not be interrupted.
Note
These methods let you manage the lifecycle and execution of threads in Java, offering flexibility and control over multithreaded applications. In the following chapters, we will explore more about these methods.
¡Gracias por tus comentarios!