0% found this document useful (0 votes)
14 views29 pages

Multi Threading

The document explains multitasking and multithreading in Java, highlighting the ability to perform multiple tasks simultaneously through threads. It details the two types of multitasking: process-based and thread-based, with Java primarily utilizing thread-based multitasking for improved program responsiveness. Additionally, it covers how to create threads in Java, the thread life cycle, and provides analogies to simplify the concepts.

Uploaded by

sssagnik7
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)
14 views29 pages

Multi Threading

The document explains multitasking and multithreading in Java, highlighting the ability to perform multiple tasks simultaneously through threads. It details the two types of multitasking: process-based and thread-based, with Java primarily utilizing thread-based multitasking for improved program responsiveness. Additionally, it covers how to create threads in Java, the thread life cycle, and provides analogies to simplify the concepts.

Uploaded by

sssagnik7
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/ 29

1

MULTI-THREADING
IN JAVA
2
WHAT IS MULTITASKING IN JAVA?
Multitasking in java means performing multiple tasks at the same time.
Just like a human can talk while walking, a java program can run multiple parts
(called tasks or threads) at once.

MULTI-TASKING

PROCESS-BASED THREAD-BASED
MULTI-TASKING MULTI-TASKING
3
TYPES OF MULTITASKING:
THERE ARE TWO TYPES OF MULTITASKING:

1.PROCESS-BASED MULTITASKING
• Running multiple programs at the same time.
• Example: Listening to music in VLC and browsing in Chrome.
2.THREAD-BASED MULTITASKING (JAVA MAINLY USES THIS)
• Running multiple threads inside a single program.
• Example: In a game, one thread plays music, another handles user input, and
another updates graphics.
4
MULTITASKING IN JAVA:
WHY USE MULTITASKING IN JAVA?
•TO MAKE PROGRAMS FASTER AND MORE RESPONSIVE.
•TO PERFORM BACKGROUND TASKS WHILE DOING OTHER THINGS.
•FOR EXAMPLE, DOWNLOADING A FILE WHILE STILL LETTING THE USER SCROLL THE
APP.

HOW JAVA DOES IT?


• JAVA SUPPORTS MULTITASKING USING THREADS.
• A THREAD IS A SMALL UNIT OF A PROGRAM.
• WE CAN CREATE A THREAD BY:
 EXTENDING THE THREAD CLASS.
 IMPLEMENTING THE RUNNABLE INTERFACE.
5
MULTI-THREADING IN JAVA:
MULTITHREADING IN JAVA MEANS RUNNING MULTIPLE THREADS (MINI-PROGRAMS)
AT THE SAME TIME WITHIN A SINGLE PROGRAM.

JUST LIKE YOUR PHONE CAN PLAY MUSIC, DOWNLOAD FILES, AND RECEIVE CALLS
AT THE SAME TIME —
JAVA CAN RUN MULTIPLE TASKS TOGETHER USING THREADS.

WHAT IS A THREAD?
Thread is a pre-defined class that is available in java.lang package.
A thread is a lightweight, independent part of a program that runs separately.
Every Java program has at least one thread — the main thread.
6
MULTI-THREADING IN JAVA:
WHY USE MULTITHREADING?
✅ To make programs faster and responsive
✅ To do multiple things at the same time
✅ Useful in games, web servers, animation, file downloads, etc.
MULTI-THREADING IN JAVA:
LET’S UNDERSTAND IT MORE SIMPLY: 7

THE KITCHEN ANALOGY


“Imagine a kitchen with only one chef. He’s making tea, then toast, then boiling
eggs — one by one. That’s like a single-threaded program — only one task at a
time.”
(Chef walks slowly across the kitchen, doing each task in order)

MULTITHREADED KITCHEN
“Now imagine the kitchen has three chefs: one making tea, one making toast,
and one boiling eggs — all at the same time! That’s multithreading.”
🧑🍳 (All chefs working at once. Tea boils while toast is flipping and eggs are
boiling — side by side)
🗨 “Just like this, java allows your program to do multiple things in parallel.”
MULTI-THREADING IN JAVA:
LET’S UNDERSTAND IT MORE SIMPLY: 8

THREADS IN A JAVA PROGRAM


“In java, each chef = thread. And your kitchen = java program.”
🗨 Thread t1 = new thread(); (chef 1 appears)
🗨 T1.Start(); (chef starts cooking)
“We can create multiple threads and start them — they’ll all run independently.”

SCHOOL ANALOGY
“ANOTHER EXAMPLE — IMAGINE YOUR SCHOOL HAS:
 ONE TEACHER TAKING ATTENDANCE
 ANOTHER COLLECTING HOMEWORK
 A THIRD WRITING ON THE BOARD”
🧑🏫🧑🏫🧑🏫 (ALL THREE TASKS HAPPENING AT ONCE IN THE CLASSROOM)
🎤 “THAT’S MULTITHREADING — EACH THREAD IS DOING A DIFFERENT JOB, AT THE SAME TIME.”
MULTI-THREADING IN JAVA:
LET’S UNDERSTAND IT MORE SIMPLY: 9

SUMMARY

Multithreading = Multiple Threads = Multiple Tasks At The Same Time


Each Thread = Mini Program That Runs Independently
start() = Begins A New Thread

“THIS MAKES OUR JAVA PROGRAMS FASTER, RESPONSIVE, AND POWERFUL!”


🚀 HOW TO CREATE A THREAD IN JAVA?
THERE ARE TWO WAYS TO CREATE THREADS: 10

✅ 1. By extending the Thread class:


The first way to create a thread is to create a new class that extends the
Thread class using the following two simple steps. This approach provides
more flexibility in handling multiple threads created using available
methods in the thread class.
STEP 1: First we need to overwrite the run() method available in the
Thread class. This method provides an entry point for the thread
and we will put our complete logic inside this method.

STEP 2: Once the thread object is created we can start it by calling


the star() method which executes a call to run() method.
🚀 HOW TO CREATE A THREAD IN JAVA?
THERE ARE TWO WAYS TO CREATE THREADS: 11

✅ 1. By extending the Thread class:


class ThreadDemo extends Thread{
public void run() {
for(int i=1; i<=10; i++){
System.out.println("Rajganj");
}
}
}

public class TestThread {

public static void main(String[] args) {


ThreadDemo td = new ThreadDemo();
td.start();

for(int i=1; i<=10; i++){


System.out.println("Jalpaiguri");
}
}
}
🚀 WHY TO USE THREAD IN JAVA?
THERE ARE TWO WAYS TO CREATE THREADS:
12
✅ 1. By extending the Thread class: class ThreadDemo extends Thread{
public void fun() {
try {
for(int i=1; i<=10; i++){
System.out.println("Rajganj");
Thread.sleep(1000);
}
} catch (InterruptedException i) {
Here I’ve created a single thread. // TODO: handle exception
}
And it takes 20 seconds to execute.
}
}

public class SingleThread {


public static void main(String[] args) throws InterruptedException {
ThreadDemo td = new ThreadDemo();
td.fun();

for(int i=1; i<=10; i++){


System.out.println("Jalpaiguri");
Thread.sleep(1000);
}
}
}
🚀 WHY TO USE THREAD IN JAVA?
THERE ARE TWO WAYS TO CREATE THREADS:
13
✅ 1. By extending the Thread class: class ThreadDemo extends Thread{
public void fun() {
try {
for(int i=1; i<=10; i++){
Here I’ve created a single thread. System.out.println("Rajganj");
Thread.sleep(1000);
And it takes 20 seconds to execute. }
} catch (InterruptedException i) {
OUTPUT: // TODO: handle exception
}

}
}

public class SingleThread {


public static void main(String[] args) throws InterruptedException {
ThreadDemo td = new ThreadDemo();
td.fun();

for(int i=1; i<=10; i++){


System.out.println("Jalpaiguri");
Thread.sleep(1000);
}
}
}
🚀 WHY TO USE THREAD IN JAVA?
THERE ARE TWO WAYS TO CREATE THREADS:
14
✅ 1. By extending the Thread class: class ThreadDemo extends Thread{
public void run() {
try {
for(int i=1; i<=10; i++){
Here I’ve used multi-threading. System.out.println("Rajganj");
Thread.sleep(1000);
And it takes 10 seconds to execute. }
} catch (InterruptedException i) {
OUTPUT: // TODO: handle exception
}

}
}

public class TestThread2 {


public static void main(String[] args) throws InterruptedException {
ThreadDemo td = new ThreadDemo();
td.start();

for(int i=1; i<=10; i++){


System.out.println("Jalpaiguri");
Thread.sleep(1000);
}
}
}
🚀 HOW TO CREATE A THREAD IN JAVA?
THERE ARE TWO WAYS TO CREATE THREADS: 15

✅ 2. By implementing the Runnable interface:


The second way to create a thread is to implement a Runnable interface
using the following three simple steps.
The first step is we need to implement a run() method provided by a
runnable interface this method provides an entry point for the thread
and will put our logic inside this method.
In the second step, we need to initiate a thread object using a
constructor where the thread object is an instance of a class that
implements the runnable interface, and the thread name is the name
given to the new thread.
And at last once a thread object is created we can start it by calling the
start() method, which executes a call to the run() method.
🚀 HOW TO CREATE A THREAD IN JAVA?
THERE ARE TWO WAYS TO CREATE THREADS: 16

✅ 2. By implementing the Runnable interface:


class RunnableDemo implements Runnable {
public void run(){ Defining a Thread
for (int i = 1; i <= 5; i++) {
System.out.println("My Child Thread...");
}

}
Thread Job
}

public class RunnableThread {


public static void main(String[] args) {
OUTPUT:
RunnableDemo rd = new RunnableDemo();

Thread t = new Thread(rd);


t.start(); //Thread call

for (int i = 1; i <= 5; i++) {


System.out.println("My Main Thread...");
}
}
}
🚀 HOW TO CREATE A THREAD IN JAVA?
✅ 2. By implementing the Runnable interface:
17
class RunnableDemo implements Runnable {
public void run(){
try {
for (int i = 1; i <= 5; i++) {
System.out.println("My Child Thread...");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
// TODO: handle exception
}
}
}

public class RunnableThread2{


public static void main(String[] args) throws InterruptedException {
RunnableDemo rd = new RunnableDemo();
OUTPUT:
Thread t = new Thread(rd);
t.start();

for (int i = 1; i <= 5; i++) {


System.out.println("My Main Thread...");
Thread.sleep(1000);
}
}
}
📘 THREAD LIFE CYCLE IN JAVA
A thread in Java is a lightweight subprocess. It goes through several 18
states during its lifetime from creation to completion.
Java uses the thread class (from java.lang package ) to create and
manage threads.

🔄 FIVE MAIN STATES OF A THREAD


1) NEW STATE (BORN)
2) RUNNABLE STATE (READY)
3) RUNNING STATE (EXECUTION)
4) BLOCKED STATE (WAITING)
5) DEAD STATE (EXIT)
📘 THREAD LIFE CYCLE IN JAVA
19
4
t.join()
BLOCKED t.sleep()
STATE t.wait()
t.resume() t.suspend()

t.stop()

t
t.start() THREAD run()
BORN READY RUNNING DEAD
SCHEDULER

1 2 3 5
📘 THREAD LIFE CYCLE IN JAVA
🟦 1. NEW STATE: 20
 Created using: thread t = new thread();
 Thread object is made, but the thread has not started executing.
🟩 2. RUNNABLE STATE:
 Invoked by: t.start();
 Thread is ready to run, but CPU has not assigned it processor time yet.
🟨 3. RUNNING STATE:
 Thread is actively executing.
 Managed by the thread scheduler (part of JVM).
🟧 4. BLOCKED / WAITING / SLEEPING:
 Blocked: waiting to acquire a lock on an object.
 Waiting: waiting indefinitely for another thread to perform a task.
 Sleeping: paused for a fixed time using Thread.sleep(ms) .
🟥 5. TERMINATED (DEAD) STATE:
 Happens when run() method completes or thread is stopped manually.
 Once terminated, a thread cannot be restarted.
21

🧵 The Life of a
Java Thread
THREAD LIFE CYCLE EXPLAINED SIMPLY
1. New State 👶 22

 Thread is created but not started.

 Example: Thread t = new Thread();

 🗨 'Hi! I’ve been created... but I’m not working yet.'


2. Runnable State ⏳ 23

 Thread is ready to run, waiting for CPU.

 Example: t.start();

 🗨 'I’m ready! Just waiting for my turn.'


3. Running State 🏃 24

 Thread is actively executing its run() method.

 🗨 'Now I’m doing my job!'


4. Blocked / Waiting / Sleeping 😴 25

 Thread is temporarily paused due to sleep(), wait(), or resource lock.

 Examples:
 Thread.sleep(1000);
 obj.wait();

 🗨 'Taking a break or waiting for access.'


5. Back to Runnable 🔄 26

 Once conditions are met, thread returns to Runnable and waits for
CPU.

 🗨 'Back in the queue and ready!'


6. Terminated State ✅ 27

 Thread has finished execution and cannot be restarted.

 🗨 'I’ve completed my mission!'


7. FULL LIFECYCLE RECAP 🔁
+----------+ start() +-----------+
28
| New |-----------------> | Runnable |
+----------+ +-----+-----+
|
v
+-----------+
| Running |
+-----+-----+
|
+------------------------+---------------------+
| | |
v v v
+------------+ +-------------+ +------------+
| Sleeping | | Waiting | | Blocked |
+------------+ +-------------+ +------------+
\______________________/|\__________________/
|
v
+----------+
| Runnable |
+----------+
|
v
+---------------+
| Terminated |
+---------------+
8. Summary Table 📋 29

STATE | DESCRIPTION
------------- | ---------------------------
 New | Thread is created
 Runnable | Ready to run
 Running | Actively executing
 Blocked | Temporarily paused
 Terminated | Execution complete

You might also like