What is Thread in Java

In Java, thread is a unit of execution within a program that can run concurrently with other threads. Each thread represents a separate flow of execution within a program, allowing different parts of the program to execute independently and simultaneously. A thread can be thought of as a lightweight process that enables a program to execute multiple tasks concurrently, thereby improving program performance and responsiveness.


There are two ways to create a thread in Java:

  1. 1. Extending the Thread class
  2. 2. Implementing the Runnable interface

Here's an example of how to create a thread by extending the Thread class:

class MyThread extends Thread { public void run() { System.out.println("MyThread running"); } } public class Main { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); } }

In this example, we create a MyThread class that extends the Thread class and overrides the run() method. We then create an instance of the MyThread class and call the start() method, which starts a new thread and calls the run() method.


Here's an example of how to create a thread by implementing the Runnable interface:

class MyRunnable implements Runnable { public void run() { System.out.println("MyRunnable running"); } } public class Main { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); } }

In this example, we create a MyRunnable class that implements the Runnable interface and overrides the run() method. We then create an instance of the MyRunnable class and pass it to a Thread object's constructor. Finally, we call the start() method on the Thread object to start a new thread and call the run() method.


In both examples, we create a new thread that runs concurrently with the main thread of the program. When we run these programs, we should see the message "MyThread running" or "MyRunnable running" printed to the console.