SlideShare a Scribd company logo
MultiThreading
By. Janmejaya
Agenda
Multithreading
Concepts
Creating
Thread
Controlling
Threads
Thread States
Summary
Multithreading
concepts
Need For Concurrency
Multi Processing
Multi Threading
Multithreading makes user-interface more
responsive
Better utilization of time
Creating
Threads
A thread represents
code that will be run
concurrently with other
code in the same
process.
Creating a Thread
• Use The Thread Class
• Use The Runnable Interface
Which
approach is
better?
Extending Thread is
Simpler.
Implementing
Runnable allows sub
classing other classes.
Extending
Thread
Extend
java.lang.Thread
Implement run
method
Implementing
Runnable
Create a Runnable Object
Create
Pass the Object to Thread Constructor
Pass
Override run method
Override
What Is
Thread
A Thread is a single sequential flow of control
within a program.
Thread does not have its own address space but
uses the memory and other resources of the
process in which it executes.
There may be several threads in one process.
The JVM manages this and shedules them.
What is
Multithreading?
Multithreading is a conceptual programming where
one program or process is divided into multiple sub
programs or tasks those are having independent
path of execution and can run in parallel.
For example one sub program can read a CSV file
and another sub program can enter the data into
DB.
A program that contains multiple flow of control is
known as multithreaded program.
Thread State
Thread
Priorities
Java assign each thread a priority, that
determines how that Thread should be
treated with respect to others.
Thread Priorities are integers that
specify relative priority of one thread to
another.
A Thread Priority is used to decide when
to switch from one running thread to the
next. This is called context switching.
Thread Priorities
• A thread can voluntarily
relinquish control. This is done by
explicit yielding, sleeping or
blocking on pending IO. In this
scenario all other threads are
examined , and the highest
priority thread that is ready to
run is given the CPU.
• A Thread can be pre-empted by a
higher priority thread. This is
called pre-emptive multi tasking.
Multitasking
Multitasking allows several activities to
occur concurrently on the computer. A
distinction is usually made between :
Process based Multitasking
Thread based Multitasking
Advantage of
thread based
multithreading
Thread share the
same address
space
Context switching
is less expensive.
Cost of
communication
between threads is
relatively low
Overview of
Thread
A thread is an independent sequential
path of execution within a program.
Many threads can run concurrently
within a program.
At run time Threads in a program exists
in a common memory space and can
therefore share both data and code.
The Main
Thread
When a standalone application run, a user thread is
automatically created to execute the main method of the
application.
From main thread child thread are spawned.
If no user threads are there ,the program terminates when
main execution finished.
All other threads are called child threads ,spawned from main
thread inheriting its child thread status.
The main method can finish , but the program will keep
running until all user threads have complted.
User Threads & Daemon Threads
The run time environment distinguishes between user threads and
daemon threads. As long as user thread is alive , the JVM does not
terminate.
A daemon thread is at the mercy of the runtime system. It is stopped if
there are no more user threads running, thus terminating the program.
Daemon thread exists only to serve user thread.
Creating
Daemon or
User Thread
Calling the setDaemon(boolean) method
of Thread class marks the status of
Thread as either Daemon or User.
This method must be called on a Thread
object before it starts.
Any attempt to change the status of the
Thread will throw an
IllegalThreadStateException.
Thread
Creation
A Thread in Java is represented by
an object of the Thread class.
Implementing thread is achieved in
one of the two ways.
Implementing the
java.lang.Runnable interface
Extending the java.lang.Thread
class
Thread class method
Thread class method
Thread class
constructor
Thread class
constructor
Synchronization
Threads share the same memory space i.e they can share resources.
However there are some critical situation where it is desirable that only one Thread
at a time has access to a shared resources.
For example crediting and debiting a shared bank account concurrently among
several users without proper discipline will harm the integrity of the account data.
Java Provides high level concepts of synchronization in order to control access to
shared resources.
Locks
A lock also called as a monitor is used to synchronize access
to a shared resource.
Threads gain access to a shared resource by first acquiring the
lock associated with the resource.
At any given time at most one thread can hold the lock and
there by have access to the shared resource.
In Java , all the objects have a lock, including arrays.
By associating a shared resource with a java object and its
lock , the object can act as a guard, ensuring synchronized
access to the resource.
Object Lock
Mechanism
• The Object lock mechanism , enforces the following rules of
synchronization.
• A thread must acquire the object lock
associated with a shared resource, before it can
enter the shared resource. The runtime system
ensures that no other thread can entered a
shared resource if another thread already holds
the object lock associated with it.
• If a thread can not immediately acquire the
object lock, it will be blocked.
• If a thread exists a shared resource , the runtime
ensures that the object lock is also relinquished.
If another thread is waiting for this object lock ,
it will be notified .
Two ways of
synchronization
• There are two ways in which
execution of code can be
synchronized:
• Synchronized Method
• Synchronized Code block
Different
way to hold
a lock
By executing a synchronized
instance method of the object.
By executing a synchronized block
that synchronizes on the object.
By executing a synchronized static
method of a class .
Thread States
New state-: A thread is created but not yet started.
Ready To run state-: when we call start() on a Thread object comes to this state waiting for TS to
get its turn.
Running state-: In this state the thread gets its turn and started executing run ().
Dead State-:Once in this state, A thread can not run again.
Non-Runnable states-: A running thread can transit to one of the non-runnable states. A thread
remains in non-runnable state until a special transition occurs.
Non-
Runnable
States
Sleeping: the thread sleeps for a specified
amount of time.
Blocked for I/O: the threads wait for
blocking operation to complete.
Blocked for join completion: The thread
awaits completion of another thread.
Waiting for notification: the thread awaits
notification from another thread.
Blocked for lock acquisition: The thread wait
to acquire the lock.
Thread.State
NEW – Created but
not yet started
RUNNABLE –
Executing the JVM
BLOCKED – blocked
for lock acquisition
WAITING- Waiting
for notify, Blocked
for join completion
TIMED_WAITING-
Sleeping, Waiting
For notify
TERMINATED-
Completed
Thread
Prorities
Threads are assigned priorities that the thread scheduler can
use to determine how the threads will be scheduled.
The TS can use thread priorities to determine which thread
gets to run.
The TS favours giving the CPU time to the thread with the
highest priority in ready to run state.
Heavy reliance on thread priorities for the behavior of a
program can make the program unportable across platforms,
as thread scheduling is host-platform dependant.
Thread
Priorities
Priorities are integer values
1-lowest (Thread.MIN_PRIORITY)
10-highest(Thread.MAX_PRIORITY)
5-normal(Thread.NORM_PRIORITY)
Thread Scheduler
Scheduler in JVM implementations usually employ one of the two
strategies.
Preemptive scheduling: If a thread with a higher priority than the current
running thread moves to the ready to run state, then the current state can
be preempted to the higher priority thread execute.
Time-sliced or Round-Robin: A running thread is allowed to execute for a
fixed length of time , after which it moves to ready to run state.

More Related Content

What's hot (20)

PDF
Spring Framework Tutorial | VirtualNuggets
Virtual Nuggets
 
PPTX
Spring Framework
tola99
 
PPTX
Introduction to Ibatis by Rohit
Rohit Prabhakar
 
PPT
Spring ppt
Mumbai Academisc
 
PPT
Java & J2EE Struts with Hibernate Framework
Mohit Belwal
 
PDF
Spring core module
Raj Tomar
 
PPTX
Java Spring
AathikaJava
 
PPTX
Spring framework-tutorial
vinayiqbusiness
 
PPTX
Java spring ppt
natashasweety7
 
PPTX
Spring Framework Rohit
Rohit Prabhakar
 
PPTX
Spring framework Introduction
Anuj Singh Rajput
 
ODP
Spring User Guide
Muthuselvam RS
 
PPTX
Spring framework
Sonal Poddar
 
PDF
Building Enterprise Application with J2EE
Calance
 
PDF
J2EE Introduction
Patroklos Papapetrou (Pat)
 
ODP
Introduction to Spring Framework and Spring IoC
Funnelll
 
PDF
Java spring framework
Rajiv Gupta
 
PPTX
Spring MVC framework
Mohit Gupta
 
PPTX
J2ee seminar
Sahil Kukreja
 
PPSX
CR Bridge Solutions Pvt Ltd. Java slides
CRBTech
 
Spring Framework Tutorial | VirtualNuggets
Virtual Nuggets
 
Spring Framework
tola99
 
Introduction to Ibatis by Rohit
Rohit Prabhakar
 
Spring ppt
Mumbai Academisc
 
Java & J2EE Struts with Hibernate Framework
Mohit Belwal
 
Spring core module
Raj Tomar
 
Java Spring
AathikaJava
 
Spring framework-tutorial
vinayiqbusiness
 
Java spring ppt
natashasweety7
 
Spring Framework Rohit
Rohit Prabhakar
 
Spring framework Introduction
Anuj Singh Rajput
 
Spring User Guide
Muthuselvam RS
 
Spring framework
Sonal Poddar
 
Building Enterprise Application with J2EE
Calance
 
J2EE Introduction
Patroklos Papapetrou (Pat)
 
Introduction to Spring Framework and Spring IoC
Funnelll
 
Java spring framework
Rajiv Gupta
 
Spring MVC framework
Mohit Gupta
 
J2ee seminar
Sahil Kukreja
 
CR Bridge Solutions Pvt Ltd. Java slides
CRBTech
 

Similar to Multithreading in java (20)

PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
KusumitaSahoo1
 
PDF
Java threads
Prabhakaran V M
 
PPT
Multithreading
F K
 
PPT
Java
Khasim Cise
 
PPTX
Multithreading programming in java
Elizabeth alexander
 
PPT
Java Multithreading
Rajkattamuri
 
PPT
Java multithreading
Mohammed625
 
PPT
Java
mdfkhan625
 
PPTX
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
PDF
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
PPTX
Multithreading in java
junnubabu
 
PPTX
Multithreading in java
Kavitha713564
 
PPTX
Multithreading in java
Kavitha713564
 
PPT
multithreading
Rajkattamuri
 
PPTX
Object-Oriented-Prog_MultiThreading.pptx
NasreenTaj20
 
PPTX
Multithreading
sagsharma
 
PPT
Md09 multithreading
Rakesh Madugula
 
PPTX
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
PPTX
Multithreading in java
Raghu nath
 
PPTX
Multi-Threading in Java power point presenetation
AshokRachapalli1
 
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
KusumitaSahoo1
 
Java threads
Prabhakaran V M
 
Multithreading
F K
 
Multithreading programming in java
Elizabeth alexander
 
Java Multithreading
Rajkattamuri
 
Java multithreading
Mohammed625
 
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Multithreading in java
junnubabu
 
Multithreading in java
Kavitha713564
 
Multithreading in java
Kavitha713564
 
multithreading
Rajkattamuri
 
Object-Oriented-Prog_MultiThreading.pptx
NasreenTaj20
 
Multithreading
sagsharma
 
Md09 multithreading
Rakesh Madugula
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
Multithreading in java
Raghu nath
 
Multi-Threading in Java power point presenetation
AshokRachapalli1
 
Ad

Recently uploaded (20)

PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Ad

Multithreading in java

  • 3. Multithreading concepts Need For Concurrency Multi Processing Multi Threading Multithreading makes user-interface more responsive Better utilization of time
  • 4. Creating Threads A thread represents code that will be run concurrently with other code in the same process. Creating a Thread • Use The Thread Class • Use The Runnable Interface
  • 5. Which approach is better? Extending Thread is Simpler. Implementing Runnable allows sub classing other classes.
  • 7. Implementing Runnable Create a Runnable Object Create Pass the Object to Thread Constructor Pass Override run method Override
  • 8. What Is Thread A Thread is a single sequential flow of control within a program. Thread does not have its own address space but uses the memory and other resources of the process in which it executes. There may be several threads in one process. The JVM manages this and shedules them.
  • 9. What is Multithreading? Multithreading is a conceptual programming where one program or process is divided into multiple sub programs or tasks those are having independent path of execution and can run in parallel. For example one sub program can read a CSV file and another sub program can enter the data into DB. A program that contains multiple flow of control is known as multithreaded program.
  • 11. Thread Priorities Java assign each thread a priority, that determines how that Thread should be treated with respect to others. Thread Priorities are integers that specify relative priority of one thread to another. A Thread Priority is used to decide when to switch from one running thread to the next. This is called context switching.
  • 12. Thread Priorities • A thread can voluntarily relinquish control. This is done by explicit yielding, sleeping or blocking on pending IO. In this scenario all other threads are examined , and the highest priority thread that is ready to run is given the CPU. • A Thread can be pre-empted by a higher priority thread. This is called pre-emptive multi tasking.
  • 13. Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between : Process based Multitasking Thread based Multitasking
  • 14. Advantage of thread based multithreading Thread share the same address space Context switching is less expensive. Cost of communication between threads is relatively low
  • 15. Overview of Thread A thread is an independent sequential path of execution within a program. Many threads can run concurrently within a program. At run time Threads in a program exists in a common memory space and can therefore share both data and code.
  • 16. The Main Thread When a standalone application run, a user thread is automatically created to execute the main method of the application. From main thread child thread are spawned. If no user threads are there ,the program terminates when main execution finished. All other threads are called child threads ,spawned from main thread inheriting its child thread status. The main method can finish , but the program will keep running until all user threads have complted.
  • 17. User Threads & Daemon Threads The run time environment distinguishes between user threads and daemon threads. As long as user thread is alive , the JVM does not terminate. A daemon thread is at the mercy of the runtime system. It is stopped if there are no more user threads running, thus terminating the program. Daemon thread exists only to serve user thread.
  • 18. Creating Daemon or User Thread Calling the setDaemon(boolean) method of Thread class marks the status of Thread as either Daemon or User. This method must be called on a Thread object before it starts. Any attempt to change the status of the Thread will throw an IllegalThreadStateException.
  • 19. Thread Creation A Thread in Java is represented by an object of the Thread class. Implementing thread is achieved in one of the two ways. Implementing the java.lang.Runnable interface Extending the java.lang.Thread class
  • 24. Synchronization Threads share the same memory space i.e they can share resources. However there are some critical situation where it is desirable that only one Thread at a time has access to a shared resources. For example crediting and debiting a shared bank account concurrently among several users without proper discipline will harm the integrity of the account data. Java Provides high level concepts of synchronization in order to control access to shared resources.
  • 25. Locks A lock also called as a monitor is used to synchronize access to a shared resource. Threads gain access to a shared resource by first acquiring the lock associated with the resource. At any given time at most one thread can hold the lock and there by have access to the shared resource. In Java , all the objects have a lock, including arrays. By associating a shared resource with a java object and its lock , the object can act as a guard, ensuring synchronized access to the resource.
  • 26. Object Lock Mechanism • The Object lock mechanism , enforces the following rules of synchronization. • A thread must acquire the object lock associated with a shared resource, before it can enter the shared resource. The runtime system ensures that no other thread can entered a shared resource if another thread already holds the object lock associated with it. • If a thread can not immediately acquire the object lock, it will be blocked. • If a thread exists a shared resource , the runtime ensures that the object lock is also relinquished. If another thread is waiting for this object lock , it will be notified .
  • 27. Two ways of synchronization • There are two ways in which execution of code can be synchronized: • Synchronized Method • Synchronized Code block
  • 28. Different way to hold a lock By executing a synchronized instance method of the object. By executing a synchronized block that synchronizes on the object. By executing a synchronized static method of a class .
  • 29. Thread States New state-: A thread is created but not yet started. Ready To run state-: when we call start() on a Thread object comes to this state waiting for TS to get its turn. Running state-: In this state the thread gets its turn and started executing run (). Dead State-:Once in this state, A thread can not run again. Non-Runnable states-: A running thread can transit to one of the non-runnable states. A thread remains in non-runnable state until a special transition occurs.
  • 30. Non- Runnable States Sleeping: the thread sleeps for a specified amount of time. Blocked for I/O: the threads wait for blocking operation to complete. Blocked for join completion: The thread awaits completion of another thread. Waiting for notification: the thread awaits notification from another thread. Blocked for lock acquisition: The thread wait to acquire the lock.
  • 31. Thread.State NEW – Created but not yet started RUNNABLE – Executing the JVM BLOCKED – blocked for lock acquisition WAITING- Waiting for notify, Blocked for join completion TIMED_WAITING- Sleeping, Waiting For notify TERMINATED- Completed
  • 32. Thread Prorities Threads are assigned priorities that the thread scheduler can use to determine how the threads will be scheduled. The TS can use thread priorities to determine which thread gets to run. The TS favours giving the CPU time to the thread with the highest priority in ready to run state. Heavy reliance on thread priorities for the behavior of a program can make the program unportable across platforms, as thread scheduling is host-platform dependant.
  • 33. Thread Priorities Priorities are integer values 1-lowest (Thread.MIN_PRIORITY) 10-highest(Thread.MAX_PRIORITY) 5-normal(Thread.NORM_PRIORITY)
  • 34. Thread Scheduler Scheduler in JVM implementations usually employ one of the two strategies. Preemptive scheduling: If a thread with a higher priority than the current running thread moves to the ready to run state, then the current state can be preempted to the higher priority thread execute. Time-sliced or Round-Robin: A running thread is allowed to execute for a fixed length of time , after which it moves to ready to run state.