Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Threads in Java | Multithreading Basics
Multithreading in Java
course content

Conteúdo do Curso

Multithreading in Java

Multithreading in Java

1. Multithreading Basics
2. Synchronized Collections
3. High-level Synchronization Mechanisms
4. Multithreading Best Practices

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.

java

Main

copy
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();

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.

java

Main

copy
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();

Thread class inheritance

Alternatively, you can inherit the Thread class and override the run() method.

java

Main

copy
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 } }

Implementation of the Runnable interface

You can also implement the Runnable interface and in it implement the run() method:

java

Main

copy
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 } }

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.

java

Main

copy
1234567891011121314151617181920212223242526
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.

java

Main

copy
123456789101112131415161718192021222324252627282930313233
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.

1. What is a thread in Java?
2. What is the difference between Thread class and Runnable interface in Java?

What is a thread in Java?

Selecione a resposta correta

What is the difference between Thread class and Runnable interface in Java?

Selecione a resposta correta

Tudo estava claro?

Seção 1. Capítulo 3
We're sorry to hear that something went wrong. What happened?
some-alt