In Java, a Thread is a lightweight process that allows concurrent execution of tasks. Multithreading improves performance by executing multiple parts of a program simultaneously.
A Thread in Java is a single unit of execution within a process. It helps execute multiple tasks concurrently. Java provides in-built support for multithreading using the Thread class and the Runnable interface.
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // starts the thread
}
}
Output: Thread is running...
Java threads help perform multiple tasks at once, utilize CPU efficiently, and improve overall application performance.
Threads lead to better CPU utilization and faster task execution. They also make applications more responsive by running independent parts of the program simultaneously.
However, threads increase programming complexity. They can cause issues like deadlocks, race conditions, and synchronization problems, which make debugging and maintenance harder.
A thread passes through several stages during its lifetime:
1. New: Thread is created but not started.
2. Runnable: Thread is ready and waiting for CPU time.
3. Running: Thread is currently executing.
4. Waiting/Blocked: Thread is temporarily inactive.
5. Terminated: Thread has completed its execution.
class LifeCycleDemo extends Thread {
public void run() {
System.out.println("Thread state: Running");
}
public static void main(String[] args) {
LifeCycleDemo t1 = new LifeCycleDemo();
System.out.println("Thread state: New");
t1.start();
System.out.println("Thread state: Runnable");
}
}
Output:
Thread state: New
Thread state: Runnable
Thread state: Running
Instead of extending the Thread class, we can implement the Runnable interface for more flexibility.
class RunnableExample implements Runnable {
public void run() {
System.out.println("Runnable thread is running...");
}
public static void main(String[] args) {
RunnableExample obj = new RunnableExample();
Thread t1 = new Thread(obj);
t1.start();
}
}
Output: Runnable thread is running...
It is recommended to use Runnable interface instead of extending Thread class. Use synchronization to prevent race conditions, and prefer the Executor framework for managing multiple threads efficiently. Avoid unnecessary thread creation to save memory and CPU resources.