Understanding Multithreading in Java with Examples
Multithreading in Java allows multiple parts of a program, called threads, to run concurrently. This helps make efficient use of the CPU and improves the performance of applications that perform multiple tasks at once.
Ways to Create a Thread
1. Extending the Thread Class
class MyThread extends Thread {
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getId());
}
}
MyThread t1 = new MyThread();
t1.start();
2. Implementing the Runnable Interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable running: " + Thread.currentThread().getId());
}
}
Thread t2 = new Thread(new MyRunnable());
t2.start();
Thread Lifecycle
- New — thread object created but not yet started
- Runnable — thread is ready to run and waiting for CPU time
- Running — thread is currently executing
- Blocked/Waiting — thread is paused, waiting for a resource or signal
- Terminated — thread has finished execution
Why Use Multithreading?
- Improves performance by running independent tasks in parallel
- Keeps applications responsive, since long tasks don't block the entire program
- Makes better use of multi-core processors
Always prefer implementing
Runnable over extending Thread when your class already extends another class, since Java doesn't support multiple inheritance of classes.Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.