There are two primary ways to create threads in Java: implementing the Runnable interface or inheriting from the Thread class. Below, I will detail both methods with code examples.
Method 1: Implementing the Runnable Interface
Implementing the Runnable interface is the preferred method for creating threads. The advantage is that it allows for multiple interface implementations, as Java does not support multiple class inheritance but does allow implementing multiple interfaces.
Steps:
- Create a class that implements the
Runnableinterface and implements therun()method. - The
run()method will define the operations performed by the thread. - Create an instance of the
Runnableinterface. - Pass this instance to the constructor of the
Threadclass to create a thread object. - Call the
start()method on the thread object to start the new thread.
Example Code:
javaclass MyRunnable implements Runnable { public void run() { System.out.println("Thread is running using Runnable interface."); } } public class Main { public static void main(String[] args) { Runnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start(); } }
Method 2: Inheriting from the Thread Class
Another way to create threads is by directly inheriting from the Thread class. While this approach is simpler to implement, it is not recommended because it restricts class extensibility, as Java does not support multiple class inheritance.
Steps:
- Create a class that inherits from the
Threadclass. - Override the
run()method to define the thread's operations. - Create an instance of this class.
- Call the
start()method on this instance to start the new thread.
Example Code:
javaclass MyThread extends Thread { public void run() { System.out.println("Thread is running by extending Thread class."); } } public class Main { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); } }
Summary
It is generally recommended to use the method of implementing the Runnable interface to create threads, as it is more flexible and allows your class to inherit from other classes. While inheriting from the Thread class is simpler, it is less flexible due to Java's single inheritance limitation. In actual development, choose the appropriate method based on specific requirements.