Table of Contents
In this tutorial, you’ll learn about Threads in Java, Why thread is used in Java, Java Thread Benefits and How to create a thread in Java, and more.
What is Thread?
A thread is a lightweight subprocess, the smallest unit of processing or we can say that a thread is a series of executed statements .The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Why thread is used in Java?
We use Threads to make Java application faster by doing multiple things at the same time. In technical terms, Thread helps you to achieve parallelism in Java programs
Java Thread Benefits
- Java Threads are lightweight compared to processes, it takes less time and resource to create a thread.
- Threads share their parent process data and code
- Context switching between threads is usually less expensive than between processes.
- Thread intercommunication is relatively easy than process communication.
Creating a Thread
There are two ways to create a thread.
- By extending Thread class
- By implementing Runnable interface.
It can be created by extending the Thread
class and overriding its run()
method:
public class Main extends Thread {
public void run() {
System.out.println("This code is running in a thread");
}
}
Another way to create a thread is to implement the Runnable
interface:
public class Main implements Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
}