![]() |
VOOZH | about |
A thread is a lightweight unit of execution that allows a Java program to perform multiple tasks concurrently. Java provides built-in support for multithreading, enabling efficient use of CPU resources and improved application performance.
There are multiple ways to create threads in Java:
The Thread class is used to create and manage threads in Java. By extending this class and overriding the run() method, a new thread can execute a task independently.
The start() method starts a new thread and moves it from the New state to the Runnable state. When scheduled by the JVM, it automatically executes the run() method.
Syntax:
class MyThread extends Thread {
public void run() {
// task to perform
}}
MyThread t = new MyThread();
t.start();
Implementation:
Welcome to GeeksforGeeks.
The Runnable interface is used to define a task that can be executed by a thread. It contains a single method, run(), which holds the code to be executed.
Note: A class implements Runnable and the task runs when a thread executes its run() method.
Syntax:
class MyTask implements Runnable {
public void run() {
// task to perform
}
}Thread t = new Thread(new MyTask());
t.start();
Implementation:
gfg main Inside run method
Lambda expressions provide a concise way to create and run threads, especially when the task is small and simple.
Note: Lambda expressions allow defining the thread task directly without creating a separate class.
Syntax:
Thread t = new Thread(() -> {
// task to perform
});
t.start();
Implementation:
Lambda Thread running
ExecutorService is a framework that manages and executes threads through a thread pool. It provides a more efficient and scalable approach to multithreading than creating threads manually.
Note: ExecutorService manages thread creation and execution automatically, improving performance and resource usage.
Syntax:
import java.util.concurrent.*;
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(() -> {
// task to perform
});
executor.shutdown();
Implementation:
Task 1 is running in pool-1-thread-1 Task 2 is running in pool-1-thread-2