ch 4
ch 4
Threads run independently but share the same 4. Thread Life Cycle in Java (5 Marks)
memory space.
A thread in Java goes through several stages from creation
Reduces CPU idle time and increases resource to termination. This is called the thread life cycle.
utilization.
✅ Stages:
Makes applications more responsive (especially
1. New – Thread is created using new Thread(), but
GUIs and servers).
not started.
✅ Advantages:
2. Runnable – After calling start(), the thread is
Efficient use of CPU ready to run and waits for CPU time.
The thread scheduler decides which thread to run and public void stopThread() {
when, based on priority and availability.
running = false;
🔁 Diagram (text):
}
New → Runnable → Running → (Blocked/Waiting) →
Terminated }
}
public class Main {
}
public static void main(String[] args) {
System.out.println("Task 1");
Destroying a Thread:
}
Java doesn't provide a direct method to forcibly destroy a
thread (like destroy()) as it can lead to inconsistent state. }
Instead, use flags to stop a thread safely:
}
class MyThread extends Thread {
public class Main { This phase ensures same keys go to the same
reducer.
public static void main(String[] args) {
Example: All ("Hello", 1) from different mappers are
Task1 t1 = new Task1(); grouped together.
Task2 t2 = new Task2(); 🧠 Think of shuffling as gathering all similar items together.
t1.start();
🔹 3. Sorting
t2.start();
Within each group of identical keys, values are
} sorted.
("cat", 1)
Shuffling + Sorting:
("dog", [1])
Reduce Phase:
("cat", 2)
("dog", 1)
✅ Final Output:
cat: 2
dog: 1
Benefits of MapReduce:
1. Scalability
2. Fault Tolerance
3. Parallel Processing
4. Simplicity