How to Create a Thread in Java
In Java, there are two primary ways to create a thread: by extending the Thread class or implementing the Runnable interface. Both methods allow you to define the code that should run in the thread.
Method 1: Extending the Thread Class
To create a thread by extending the Thread
class, you need to follow these steps:
- Create a new class that extends the
Thread
class. - Override the
run()
method to define the code that will be executed in the thread. - Create an instance of your class and call the
start()
method to begin execution.
Example of Extending Thread:
Code Example 1
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
public class ThreadCreation {
public static void main(String[] args) {
MyThread thread = new MyThread(); // Create a new thread
thread.start(); // Start the thread
}
}
Method 2: Implementing the Runnable Interface
An alternative way to create a thread is to implement the Runnable
interface. This is particularly useful if your class already extends another class (since Java does not support multiple inheritance). The steps are:
- Create a new class that implements the
Runnable
interface. - Override the
run()
method to define the code to be executed. - Create an instance of the class and pass it to a
Thread
object. Call thestart()
method on the thread.
Example of Implementing Runnable:
Code Example 2
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread is running...");
}
}
public class RunnableThread {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable(); // Create a Runnable instance
Thread thread = new Thread(myRunnable); // Create a thread with the Runnable
thread.start(); // Start the thread
}
}
Output:
Thread is running...
Runnable thread is running...
Runnable thread is running...
Key Points:
- Use Thread class if you only need to create a thread and do not need to extend any other class.
- Use Runnable interface if you need to inherit from another class or want to separate the thread logic from the thread execution.
- The
start()
method initializes the thread and calls therun()
method in a new call stack. - Creating multiple threads using the
Runnable
interface allows for better management of resources.
By mastering these methods, you can effectively create and manage threads in your Java applications, leading to improved performance and responsiveness.