0% found this document useful (0 votes)
3 views21 pages

Multi Threading

Multithreading in Java allows multiple threads to run concurrently within a single program, enhancing performance and CPU utilization. Java supports multithreading through the Thread class and Runnable interface, with a defined lifecycle consisting of five states: New, Runnable, Running, Blocked, and Terminated. Key methods include start(), sleep(), join(), and synchronized, which is crucial for preventing race conditions when accessing shared resources.

Uploaded by

letsknow77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

Multi Threading

Multithreading in Java allows multiple threads to run concurrently within a single program, enhancing performance and CPU utilization. Java supports multithreading through the Thread class and Runnable interface, with a defined lifecycle consisting of five states: New, Runnable, Running, Blocked, and Terminated. Key methods include start(), sleep(), join(), and synchronized, which is crucial for preventing race conditions when accessing shared resources.

Uploaded by

letsknow77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Java Multi Threading

🔥 What is Multithreading in Java?


Multithreading is a technique where multiple threads run at the same time within
a single program.

🧠 Think of it Like This:


Imagine you are watching a YouTube video and at the same time:
✅ The video is playing 🎥
✅ You are typing a comment 💬
✅ The video is buffering in the background ⏳
All these tasks are happening simultaneously—this is multithreading in action!

🏗 Key Concepts of Multithreading


1️⃣ Process vs. Thread
🔹 Process: A program in execution. (e.g., Chrome, VS Code)
🔹 Thread: A smaller part of a process that runs independently.
A process can have multiple threads running at the same time.
💡 Example: A browser has multiple tabs. Each tab is a thread of the browser
process.

2️⃣ How Java Supports Multithreading?


Java provides two ways to create threads:

1. Extending the Thread class 🏛


2. Implementing the Runnable interface 🎭
🛠 Method 1: Extending the Thread class

Java Multi Threading 1


class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " +
i);
}
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

t1.start(); // Start Thread 1


t2.start(); // Start Thread 2
}
}

✅ Here, t1.start(); and t2.start(); run simultaneously (not one after another).

🛠 Method 2: Implementing Runnable Interface

class MyRunnable implements Runnable {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " +
i);
}
}
}

public class RunnableExample {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());

Java Multi Threading 2


Thread t2 = new Thread(new MyRunnable());

t1.start(); // Start Thread 1


t2.start(); // Start Thread 2
}
}

✅ Here, we implement Runnable instead of extending Thread , which is a better


approach in Java.

🕹 Thread Methods You Must Know


Method Description
start() Starts a new thread
run() Defines the task of a thread (but doesn't start it directly)
sleep(ms) Pauses thread for ms milliseconds
join() Waits for another thread to finish
setPriority(int) Sets thread priority (1-10)
getName() Gets thread name

💡 Example: Using sleep()

class MyThread extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " +
i);
try {
Thread.sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Java Multi Threading 3


}
}

🔄 Thread Lifecycle (Life Cycle of a Thread)


A thread in Java goes through 5 stages:

1️⃣ New (Created) → Thread t = new Thread();

2️⃣ Runnable (Ready to Run) → t.start();

3️⃣ Running (Executing) → run() is running

4️⃣ Blocked/Waiting (Paused temporarily) → sleep(), wait(), join()

5️⃣ Terminated (Dead) → Thread execution is complete


⚡ Multithreading Advantages
✔ Faster execution (better CPU utilization)
✔ Can perform multiple tasks at the same time
✔ Improves performance in large applications
⚠ Multithreading Issues & Solutions
❌ Problem: Race Condition
🔹 When two threads try to update a shared resource at the same time, it can
cause unexpected results.

🔹 Solution: Use synchronized keyword to avoid conflicts.


class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

Java Multi Threading 4


public int getCount() {
return count;
}
}

public class SyncExample {


public static void main(String[] args) {
Counter c = new Counter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) c.increment();
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) c.increment();
});

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Final Count: " + c.getCount()); // Expected: 2000


}
}

🔹 Why use synchronized ? It prevents both threads from modifying count at the
same time.

🎯 Where is Multithreading Used in Real Life?


Java Multi Threading 5
✔ Game Development 🎮 (Multiple players, animations, sound)
✔ Web Servers 🌐 (Handling multiple client requests)
✔ Banking Applications 💳 (Multiple transactions at the same time)
✔ Video Streaming 📹 (Playing, buffering, downloading in parallel)
🎉 Summary
🔹 Multithreading allows multiple tasks to run at the same time.
🔹 Java supports Thread class & Runnable interface to create threads.
🔹 The thread lifecycle has 5 states.
🔹 Synchronization is used to prevent data inconsistency.
🔹 Used in games, web servers, banking, and more!
🖼 Diagram: Java Thread Lifecycle
[New] (Thread Created)
|
v
[Runnable] ---> (t.start())
|
v
[Running] ---> (Executing run() method)
| |
| v
| [Blocked/Waiting] ---> (t.sleep(), t.join(), wait())
| |
| v
----> [Terminated] ---> (Thread finished)

Thread Lifecycle Explanation


1️⃣ New → Thread is created using new Thread()

Java Multi Threading 6


2️⃣ Runnable → Thread is ready but waiting for CPU
3️⃣ Running → Thread is executing run()

4️⃣ Blocked/Waiting → Thread is paused due to sleep() , join() , or wait()

5️⃣ Terminated → Thread completes execution


🛠 Java Thread Methods with Examples
1️⃣ start() - Starts a Thread
💡 Moves thread from "New" → "Runnable" → "Running"
class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
}

public class StartExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Starts a new thread
}
}

2️⃣ sleep(ms) - Pause a Thread Temporarily


💡 Moves thread from "Running" → "Blocked/Waiting"
class SleepThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " +
i);
try {
Thread.sleep(1000); // Pause for 1 second

Java Multi Threading 7


} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class SleepExample {


public static void main(String[] args) {
SleepThread t1 = new SleepThread();
t1.start();
}
}

3️⃣ join() - Wait for a Thread to Finish


💡 Moves thread from "Runnable" → "Blocked/Waiting"
class JoinThread extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " +
i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class JoinExample {


public static void main(String[] args) {
JoinThread t1 = new JoinThread();

Java Multi Threading 8


JoinThread t2 = new JoinThread();

t1.start();
try {
t1.join(); // Main thread waits for t1 to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}

📝 Main thread waits for t1 to finish before starting t2

4️⃣ setPriority() - Change Thread Priority


💡 Affects thread execution order (1 = lowest, 10 = highest)
class PriorityThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " Priority: " + Thr
ead.currentThread().getPriority());
}
}

public class PriorityExample {


public static void main(String[] args) {
PriorityThread t1 = new PriorityThread();
PriorityThread t2 = new PriorityThread();

t1.setPriority(Thread.MIN_PRIORITY); // Priority 1
t2.setPriority(Thread.MAX_PRIORITY); // Priority 10

t1.start();
t2.start();

Java Multi Threading 9


}
}

🔹 Higher priority threads may execute first but not always (depends on CPU
scheduling).

5️⃣ synchronized - Prevent Data Conflicts


💡 Ensures only one thread can modify data at a time
class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;
}
}

public class SyncExample {


public static void main(String[] args) {
Counter c = new Counter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) c.increment();
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) c.increment();
});

t1.start();
t2.start();

Java Multi Threading 10


try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Final Count: " + c.getCount()); // Should be 2000


}
}

✅ Without synchronized , count might not reach 2000 due to race conditions.

🎯 Final Summary
✔ Multithreading allows multiple tasks to run simultaneously
✔ Threads have 5 states: New → Runnable → Running → Blocked → Terminated

✔ Important methods:
start() → Starts a thread

sleep(ms) → Pauses a thread

join() → Waits for another thread to finish

setPriority() → Sets thread execution priority

synchronized → Avoids race conditions

🔹 Basic Level
1️⃣ Create a simple thread using
Thread class

Runnable interface

2️⃣ Write a program where two threads print numbers from 1 to 10.

Java Multi Threading 11


Thread 1 should print odd numbers

Thread 2 should print even numbers

3️⃣ Modify the above program using so that even numbers print only after
join()

odd numbers finish.


4️⃣ Use to make a thread pause for 2 seconds before printing each
sleep()

number from 1 to 5.

🔹 Intermediate Level
5️⃣ Create a multi-threaded program where:
Thread-1 prints A to Z

Thread-2 prints 1 to 26

Both threads should run simultaneously

6️⃣ Demonstrate by creating three threads with different priorities and


setPriority()

checking their execution order.


7️⃣ Write a program where multiple threads increment a shared counter.
Run it without synchronization and see inconsistent results

Add synchronized to fix race conditions

🔹 Advanced Level
8️⃣ Implement a Producer-Consumer problem using multithreading and wait() &
notify() .

Producer thread generates random numbers

Consumer thread retrieves and prints the numbers

9️⃣ Create a program where multiple users (threads) try to book train tickets
(shared resource).

Prevent race conditions using synchronized

🔟 Develop a banking system with multiple threads where:


One thread deposits money

Java Multi Threading 12


Another thread withdraws money

Ensure proper balance updates using synchronization

🔥 Real-World Mini Project Idea


📌 Multi-threaded File Downloader
Create a program where multiple threads download different parts of a file
simultaneously

Use ExecutorService for thread management

🚀
Synchronization in Java (With Diagram &
Examples)
🔹 What is Synchronization?
Synchronization in Java is used to control access to shared resources in a multi-
threaded environment to prevent race conditions. It ensures that only one thread
can access a critical section at a time.

🖼 Diagram: Race Condition vs. Synchronization


🔴 Without Synchronization (Race Condition)
Thread 1 Thread 2
| |
count++ ---> | ---> count++ ---> Wrong Value!

👆 Here, both threads modify the same variable at the same time, leading to
inconsistent results.

✅ With Synchronization (Safe)

Java Multi Threading 13


Thread 1 Thread 2
| |
(Lock Acquired) | | (Waits)
count++ | ---> |
(Lock Released) | | (Now Executes Safely)

👆 Only one thread executes at a time, preventing data corruption.


🔹 Types of Synchronization in Java
1️⃣ Synchronized Method → Locks the entire method
2️⃣ Synchronized Block → Locks only a part of the method
3️⃣ Static Synchronization → Locks a static method (shared by all threads)
4️⃣ Inter-Thread Communication ( , ) → Allows threads to coordinate
wait() notify()

🔥 1️⃣ Synchronized Method


👉 Use to lock an entire method.
synchronized

📌 Example: Fixing Race Condition in a Bank Account


class BankAccount {
private int balance = 1000;

public synchronized void withdraw(int amount) { // Synchronized method


if (balance >= amount) {
System.out.println(Thread.currentThread().getName() + " is withdrawin
g: " + amount);
balance -= amount;
System.out.println("Remaining Balance: " + balance);
} else {
System.out.println(Thread.currentThread().getName() + " Not Enough
Balance!");
}
}

Java Multi Threading 14


}

public class SyncMethodExample {


public static void main(String[] args) {
BankAccount account = new BankAccount();

Thread t1 = new Thread(() -> account.withdraw(700), "User 1");


Thread t2 = new Thread(() -> account.withdraw(500), "User 2");

t1.start();
t2.start();
}
}

✅ Ensures only one thread can withdraw at a time.


🔥 2️⃣ Synchronized Block
👉 Use to lock only a specific section of code instead of the whole
synchronized

method.
📌 Example: Ticket Booking System
class TicketCounter {
private int availableTickets = 5;

public void bookTicket(String name, int tickets) {


System.out.println(name + " is trying to book " + tickets + " tickets.");

synchronized (this) { // Synchronized Block


if (tickets <= availableTickets) {
System.out.println(name + " successfully booked " + tickets + " tick
ets.");
availableTickets -= tickets;
} else {
System.out.println("Not enough tickets for " + name);

Java Multi Threading 15


}
}
}
}

public class SyncBlockExample {


public static void main(String[] args) {
TicketCounter counter = new TicketCounter();

Thread t1 = new Thread(() -> counter.bookTicket("Alice", 3));


Thread t2 = new Thread(() -> counter.bookTicket("Bob", 3));

t1.start();
t2.start();
}
}

✅ Only the ticket booking process is synchronized. The print statements can
still run in parallel!

🔥 3️⃣ Static Synchronization


👉 Use in static methods to lock a shared resource across all objects.
synchronized

📌 Example: Shared Printer


class Printer {
public static synchronized void printDocument(String doc) {
System.out.println(Thread.currentThread().getName() + " is printing: " +
doc);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " finished printin

Java Multi Threading 16


g.");
}
}

public class StaticSyncExample {


public static void main(String[] args) {
Thread t1 = new Thread(() -> Printer.printDocument("File1.pdf"), "User
1");
Thread t2 = new Thread(() -> Printer.printDocument("File2.pdf"), "User
2");

t1.start();
t2.start();
}
}

✅ Ensures only one document prints at a time, even across different objects!
🔥 4️⃣ Inter-Thread Communication ( wait() , notify() )
👉 Threads can "wait" and "notify" each other to coordinate execution.
📌 Example: Producer-Consumer Problem
class SharedResource {
private int item = 0;
private boolean available = false;

public synchronized void produce() {


try {
while (available) {
wait(); // Wait if an item is already available
}
item++;
System.out.println("Produced item: " + item);
available = true;

Java Multi Threading 17


notify(); // Notify consumer to consume
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public synchronized void consume() {


try {
while (!available) {
wait(); // Wait if no item is available
}
System.out.println("Consumed item: " + item);
available = false;
notify(); // Notify producer to produce more
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class WaitNotifyExample {


public static void main(String[] args) {
SharedResource resource = new SharedResource();

Thread producer = new Thread(() -> {


for (int i = 0; i < 5; i++) resource.produce();
});

Thread consumer = new Thread(() -> {


for (int i = 0; i < 5; i++) resource.consume();
});

producer.start();
consumer.start();

Java Multi Threading 18


}
}

✅ Producer waits if an item exists; Consumer waits if no item exists.


🎯 Final Summary
✔ Synchronization is needed when multiple threads access a shared resource
✔ Avoids race conditions and data inconsistency
✔ Techniques:
synchronized method → Locks whole method

synchronized block → Locks a part of the method

Static synchronization → Locks a shared resource across objects

Inter-thread communication ( wait() , notify() ) → Helps threads coordinate

🔹 Basic Level
1️⃣ Create a synchronized method in a class to allow two users to
BankAccount

withdraw money safely.


2️⃣ Create two threads that try to modify a shared counter.
First, run it without synchronization and observe race conditions.

Then, add synchronization to fix the issue.

3️⃣ Write a program where two threads print numbers from 1 to 10.
Thread-1: Prints odd numbers

Thread-2: Prints even numbers

Ensure the correct sequence using synchronized and wait/notify.

🔹 Intermediate Level
4️⃣ Implement a ticket booking system where multiple users (threads) try to book
seats.

Java Multi Threading 19


Use synchronized block to prevent overselling tickets.

5️⃣ Create a Printer class with a printDocument() method.

Use static synchronization so that only one document prints at a time, even
across different threads.

6️⃣ Modify a shared list using multiple threads:


One thread adds numbers to the list.

Another thread removes numbers.

Use synchronized methods to ensure thread safety.

🔹 Advanced Level
7️⃣ Implement the Producer-Consumer problem using wait() and notify()
methods.
8️⃣ Create a multi-threaded ATM system where multiple users can:
Check balance

Deposit money

Withdraw money

Synchronize the methods to prevent incorrect balance updates.

9️⃣ Implement a multi-threaded restaurant ordering system:


Chef (Producer) prepares food and adds it to a queue.

Waiter (Consumer) serves food from the queue.

Use wait() and notify() to coordinate between threads.

🔟 Build a multi-threaded file downloader where:


Each thread downloads a part of the file.

Use synchronization to merge the downloaded parts correctly.

🔥 Bonus Challenge (Real-World Project Idea)


📌 Thread-Safe Chat Application
Java Multi Threading 20
Build a simple chat server where multiple users (threads) send messages.

Use synchronization to ensure messages don’t overlap.

Store chat logs safely using synchronized methods.

Let me know if you need hints, solutions, or explanations for any question! 🚀😊

Java Multi Threading 21

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy