Detailed Notes on Java Threads
1. What is a Thread?
A thread is a lightweight process that allows parallel execution within a program. Threads run in the same memory
space but each has its own execution flow. Threads are useful for concurrent tasks like downloading files, processing
data, etc.
In single-threaded applications, all tasks are done one at a time. In multi-threaded applications, tasks can run
simultaneously.
2. Creating Threads in Java
There are two ways to create a thread in Java:
1. By extending the Thread class.
2. By implementing the Runnable interface.
Example 1: Extending Thread Class
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
Explanation: The MyThread class extends Thread and overrides the run() method. The start() method initiates thread
execution.
Example 2: Implementing Runnable Interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread is running");
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
Explanation: MyRunnable implements Runnable and defines a task. The Thread object is created and executes the task
in a separate thread.
3. Thread Lifecycle
The lifecycle of a thread in Java consists of several stages:
1. New: Thread is created but not started.
2. Runnable: Thread is ready to run or running.
3. Running: Thread is executing.
4. Blocked/Waiting: Thread is waiting for resources or another thread.
5. Terminated: Thread execution is complete.
4. Thread Methods
Key methods:
- start(): Begins thread execution.
- run(): The task for the thread.
- sleep(): Pauses thread for a specified time.
- join(): Waits for a thread to complete.
- yield(): Pauses current thread to allow other threads of the same priority to execute.
5. Synchronization
Synchronization prevents multiple threads from accessing shared resources at the same time.
Example without synchronization may lead to inconsistent results. Adding synchronized keyword ensures only one
thread can access the resource at a time.
6. Deadlock
Deadlock occurs when two or more threads are blocked forever, waiting for each other to release resources. Proper
synchronization and design help avoid deadlock.