How is a thread created in Java

In Java, a thread can be created in two main ways: by extending the `Thread` class or implementing the `Runnable` interface. Each method has its own advantages depending on the requirements of the application.

Creating a Thread by Extending the Thread Class

When you extend the `Thread` class, you override its `run()` method to define the code that should execute in the thread.

class MyThread extends Thread { public void run() { System.out.println("Thread using Thread class is running"); } } MyThread thread = new MyThread(); thread.start();

Creating a Thread by Implementing the Runnable Interface

By implementing the `Runnable` interface, you can define your task in the `run()` method. This approach is often preferred as it allows your class to extend another class.

class MyRunnable implements Runnable { public void run() { System.out.println("Thread using Runnable interface is running"); } } Thread thread = new Thread(new MyRunnable()); thread.start();

Java threads create thread in Java Java multithreading Runnable interface Thread class