Explain Thread in Java
A thread in Java is a lightweight subprocess, the smallest unit of processing. It is a path of execution within a program. Threads allow a program to operate more efficiently by doing multiple things at the same time. They can be created by implementing the Runnable interface or by extending the Thread class.

Table of Contents
Advantages Thread in Java
- Concurrency: Threads allow concurrent execution of two or more parts of a program, improving performance.
- Resource Sharing: Threads share the same memory space, which makes it easy to share data between them.
- Responsiveness: Threads can make a user interface more responsive by performing long-running operations in the background.
- Disadvantages:
- Complexity: Writing, debugging, and maintaining multi-threaded programs can be more complex.
- Synchronization Issues: Threads share resources which can lead to synchronization issues if not managed correctly.
- Context Switching: Frequent switching between threads can lead to performance overhead.
Example
Creating a thread by extending the Thread class and implementing the Runnable interface.
java
// Creating a thread by extending the Thread class
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
// Creating a thread by implementing the Runnable interface
class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
// Creating and starting thread by extending Thread class
MyThread t1 = new MyThread();
t1.start();
// Creating and starting thread by implementing Runnable interface
Thread t2 = new Thread(new MyRunnable());
t2.start();
}
}
Thread in Java Example:
MyThread class extends the Thread class and overrides the run method to define the code that should be executed by the thread. MyRunnable class implements the Runnable interface and overrides the run method. In the main method, two threads are created and started, one from the MyThread class and the other from the MyRunnable class.