There are two primary ways to create threads in Java:
-
Inheriting the Thread Class:
- First, define a class that extends
Thread. - Then, override the
run()method in this class and place the code you want the thread to execute inside therun()method. - Create an instance of this class that extends
Threadand call thestart()method on the instance to start the thread.
Example code:
javaclass MyThread extends Thread { public void run(){ System.out.println("My thread is running"); } } public class TestThread { public static void main(String args[]) { MyThread t = new MyThread(); t.start(); // Start the thread } } - First, define a class that extends
-
Implementing the Runnable Interface:
- Define a class that implements the
Runnableinterface. - Implement the
run()method of this interface and place the code you want to run in the thread inside therun()method. - Create an instance of this class and pass it as a parameter to the
Threadconstructor to create a thread object. - Call the
start()method on the thread object to start the thread.
Example code:
javaclass MyRunnable implements Runnable { public void run(){ System.out.println("Thread created via Runnable interface"); } } public class TestRunnable { public static void main(String args[]) { MyRunnable myRunnable = new MyRunnable(); Thread t = new Thread(myRunnable); t.start(); // Start the thread } } - Define a class that implements the
These two methods essentially create a block of code that can run independently, and through the start() method, have the Java Virtual Machine (JVM) call the run() method of this block. Using the Runnable interface is more flexible because Java does not support multiple inheritance; therefore, if your class has already extended another class, you must use the Runnable interface to create threads.