In Java, a Thread is a lightweight process that enables multitasking in a Java program. It is a path of execution within a program, allowing the program to perform multiple tasks simultaneously or concurrently. Each thread has its own execution context, including its own stack, but shares the process’s memory space, such as variables and methods, with other threads.
Important Points of Java Thread
1. Multithreading: Java allows multithreading, meaning multiple threads can run concurrently, sharing the same resources but working independently.
2. Thread Class: In Java, a thread is represented by the Thread class, which is part of java.lang package.
3. Runnable Interface: Threads can also be created by implementing the Runnable interface, which is often used to define tasks that can be run concurrently.
How to create Thread?
There are two common ways to create and run a thread in Java.
- By extending the Thread class.
- By implementing the Runnable interface.
1. Create Thread by extending the Thread class
In this method, you create a subclass of the Thread class and override its run() method, which contains the code that will be executed by the thread.
Example:
//MyThread.java file
// Example of extending Thread class
class MyThread extends Thread {
public void run() {
// Code to be executed by the thread
System.out.println("My thread is running");
}
}
public class Main {
public static void main(String[] args) {
// Creating and starting the thread
MyThread thread = new MyThread();
thread.start(); // Starts the thread, which invokes the run() method
}
}
Output:
Explanation:
- MyThread is a subclass of Thread.
- The run() method contains the code that the thread will execute.
- The start() method is called to begin the thread’s execution. This method internally calls the run() method.
2. Create Thread by the Runnable Interface
In this approach, the Runnable interface is implemented, and its run() method is overridden.
//Main.java file
// Example of implementing Runnable interface
class MyRunnable implements Runnable {
public void run() {
// Code to be executed by the thread
System.out.println("Thread is running from Runnable");
}
}
public class Main {
public static void main(String[] args) {
// Creating a Runnable object
MyRunnable myRunnable = new MyRunnable();
// Creating a thread by passing the Runnable object to the Thread constructor
Thread thread = new Thread(myRunnable);
// Starting the thread
thread.start(); // Starts the thread and invokes the run() method
}
}
Output:
Explanation:
- MyRunnable implements the Runnable interface and defines the run() method.
- The Thread class is instantiated by passing the Runnable object (myRunnable) to its constructor.
- The start() method is called to begin thread execution.