SlideShare a Scribd company logo
2
Most read
6
Most read
19
Most read
Multithreading Parag Shah Adaptive Software Solutions http://www.adaptivelearningonline.net
Agenda Multithreading concepts Creating threads Controlling threads Thread states Summary
Multithreading concepts Multithreading concepts Creating threads Controlling threads Thread states Summary
Multithreading concepts Need for concurrency Multi processing Multi threading Multi threading makes user interfaces more responsive Multi threading makes better utilization of time when the program is blocking for IO
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  Pros and Cons Extending thread is simpler Implementing Runnable allows subclassing other classes
Creating Threads – Extending Thread Extend java.lang.Thread Implement the run method See  [SimpleThread.java]
Creating Threads – Implementing Runnable Extend java.lang.Thread Implement the run mthod See  [SimpleRunnable.java] A Runnable cannot throw a checked exception
Thread Priorities Priorities are between 1 – 10 Best to use the constants defined in Thread MAX_PRIORITY MIN_PRIORITY NORM_PRIORITY Uses of thread priority
States Of A Thread A thread can be in any one of these 4 states New: The thread object has been created but it has not been initialized Runnable: The thread object is ready to run whenever the CPU gives it a time slot Blocked: The thread could be run, but is currently not in a runnable state Dead: The thread has terminated
Controlling Thread Behavior Yielding Sleeping Setting Priorities Joining
Controlling Thread Behavior Yielding A thread can be made to yield when it comes to a point when the CPU can be relinquished to another thread Yielding is done by calling the yield() method A call to yield() is a hint to the underlying operating system. It does not guarantee that the CPU will be immediately given to another thread See  [SimpleYieldingThread.java]
Controlling Thread Behavior Sleeping A thread can be put to sleep for xxx ms Use the sleep(long x) call on the thread to put it to sleep for x ms The thread is guaranteed to sleep for x ms It may take more than that for the scheduler to give it control It may be interrupted by another thread See  [SimpleThread.java]
Controlling Thread Behavior Priorities Every thread can have a priority Scheduler will choose thread with highest priority for running first Exact mechanism of choosing the thread is indeterminate JDK supports 10 priority levels For portability it is best to use one of the predefined  (MAX_PRIORITY, NORM_PRIORITY, MIN_PRIORITY) priority levels
Controlling Thread Behavior Joining Another Thread Joining a thread is the process of suspending till the other thread completes execution Join can be called with or without a timeout Exercise SimpleJoiningThread.java
Some Deprecated Methods Deprecated methods suspend & resume stop & destroy These methods are deadlock prone An alternate mechanism for stopping threads
Sharing Resources In A  Multithreaded Environment Multiple threads may try to access the same resource The point at which a thread will be suspended and another will resume is indeterminate A thread may not have finished totally processing a data structure before it is suspended.  Another thread accessing the same data structure may find it in an improper state
Controlling Access To Shared Resources Put the shared resource in an object Make all methods in the object which access the shared resource,  synchronized Every object has a lock (monitor) Before a thread enters a synchronized method it must obtain the lock The lock is released when the thread leaves the synchronized method Only one thread can have a lock to an object at a time Synchronize a critical section on an object
Atomic Operations Atomic operations are those operations that are guaranteed to be completed before a context switch Simple assignments and 'returning values' are some atomic operations An exception is when dealing with double and long values Be careful while omitting the synchronized keyword when multiple methods are accessing the shared resource
Thread Blocking A thread can be blocked due to one of the following reasons It is waiting for I/O It has called its sleep(long ms) It has called the wait method The thread has called join on another thread The thread has called a synchronized method/block on another object and the lock is unavailable
Using wait() and notify() with threads sleep(long ms) does not release the locks held by that thread Use wait() with notify() or notifyAll() instead See  [WaitNotifyThread.java]
Deadlock What is deadlock The dining philosophers problem Conditions for a deadlock to occur At least one resource used by threads is not shareable At least one thread holds a resource and is waiting on another resource which is being held by another thread A resource cannot be taken away from a thread A circular wait happens
Threading In JDK 1.5 JDK 1.5 has increased support for threading Has a new concurrency packages java.util.concurrent java.util.concurrent.atomic java.util.concurrent.locks
Summary It is important to understand when to use threads Caution must be exercised while writing multi-threaded code Thorough testing is recommended It is important to understand which classes and methods should be made thread safe
Where to Get More Information Bruce Eckel's – Thinking In Java Taming Java Threads – Allen Holub

More Related Content

PPTX
PPT
Java And Multithreading
PPTX
Multithreading in java
PDF
Threads concept in java
PDF
Java threading
PDF
Life cycle-of-a-thread
PDF
Java threads
PPSX
Exception Handling
Java And Multithreading
Multithreading in java
Threads concept in java
Java threading
Life cycle-of-a-thread
Java threads
Exception Handling

What's hot (20)

PPTX
Multithreading in java
PDF
Java Thread Synchronization
PPTX
Jdbc ppt
PDF
Java thread life cycle
PPT
Java Networking
PPT
Java multi threading
PDF
Oops concepts || Object Oriented Programming Concepts in Java
PPTX
Exceptions in Java
PPTX
Exception Handling in Java
PPT
Jsp ppt
PPTX
JAVA AWT
PPTX
Multi-threaded Programming in JAVA
PPTX
Inter Thread Communicationn.pptx
PPTX
Java Server Pages(jsp)
PPTX
for loop in java
PDF
Monitors
PPS
Java Exception handling
ODP
OOP java
PPTX
MULTI THREADING IN JAVA
PPT
Thread model in java
Multithreading in java
Java Thread Synchronization
Jdbc ppt
Java thread life cycle
Java Networking
Java multi threading
Oops concepts || Object Oriented Programming Concepts in Java
Exceptions in Java
Exception Handling in Java
Jsp ppt
JAVA AWT
Multi-threaded Programming in JAVA
Inter Thread Communicationn.pptx
Java Server Pages(jsp)
for loop in java
Monitors
Java Exception handling
OOP java
MULTI THREADING IN JAVA
Thread model in java
Ad

Similar to Multithreading In Java (20)

PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
PPT
Java Multithreading and Concurrency
PPT
multithreading
PPT
Java Multithreading
PPT
Java multithreading
PPT
Multithreading
 
PPT
PPT
PPT
Programming - Java-Threads-and-Synchronization.ppt
PPTX
Threads in Java
PPTX
Multithreading
PPT
Md09 multithreading
PPTX
MSBTE Computer Engineering JPR java. multi. threading.pptx
PPTX
econtent thread in java.pptx
PPTX
Thread priorities in java
PPTX
Multithreading in java
PDF
Java Multithreading Interview Questions PDF By ScholarHat
PPTX
Multithreading programming in java
PPTX
unit3multithreadingppt-copy-180122162204.pptx
PPTX
unit3 Exception Handling multithreadingppt.pptx
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
Java Multithreading and Concurrency
multithreading
Java Multithreading
Java multithreading
Multithreading
 
Programming - Java-Threads-and-Synchronization.ppt
Threads in Java
Multithreading
Md09 multithreading
MSBTE Computer Engineering JPR java. multi. threading.pptx
econtent thread in java.pptx
Thread priorities in java
Multithreading in java
Java Multithreading Interview Questions PDF By ScholarHat
Multithreading programming in java
unit3multithreadingppt-copy-180122162204.pptx
unit3 Exception Handling multithreadingppt.pptx
Ad

More from parag (18)

ODP
Application Development Using Java - DIYComputerScience Course
ODP
Version Control With svn Setting The Stage
ODP
Effective exceptions
ODP
Data structures
ODP
Building Internet Reputation
ODP
General method best_practices
ODP
Make defensive copies
ODP
Check methods params_for_validity
ODP
Double checkedlockingjavasingletons
ODP
Uml
PDF
Internet And New Media For Teaching
ODP
Java Collections
ODP
Blogging and The Learning Professional
PPT
Inner Classes
PPT
Interfaces In Java
ODP
IO In Java
ODP
Exception Handling In Java
PPT
Goals Of Software Design - The main goals
Application Development Using Java - DIYComputerScience Course
Version Control With svn Setting The Stage
Effective exceptions
Data structures
Building Internet Reputation
General method best_practices
Make defensive copies
Check methods params_for_validity
Double checkedlockingjavasingletons
Uml
Internet And New Media For Teaching
Java Collections
Blogging and The Learning Professional
Inner Classes
Interfaces In Java
IO In Java
Exception Handling In Java
Goals Of Software Design - The main goals

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Electronic commerce courselecture one. Pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
A Presentation on Artificial Intelligence
PPTX
Machine Learning_overview_presentation.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
MYSQL Presentation for SQL database connectivity
Dropbox Q2 2025 Financial Results & Investor Presentation
Building Integrated photovoltaic BIPV_UPV.pdf
The AUB Centre for AI in Media Proposal.docx
Electronic commerce courselecture one. Pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Programs and apps: productivity, graphics, security and other tools
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
The Rise and Fall of 3GPP – Time for a Sabbatical?
sap open course for s4hana steps from ECC to s4
Chapter 3 Spatial Domain Image Processing.pdf
A comparative analysis of optical character recognition models for extracting...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
A Presentation on Artificial Intelligence
Machine Learning_overview_presentation.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Reach Out and Touch Someone: Haptics and Empathic Computing
20250228 LYD VKU AI Blended-Learning.pptx
NewMind AI Weekly Chronicles - August'25-Week II

Multithreading In Java

  • 1. Multithreading Parag Shah Adaptive Software Solutions http://www.adaptivelearningonline.net
  • 2. Agenda Multithreading concepts Creating threads Controlling threads Thread states Summary
  • 3. Multithreading concepts Multithreading concepts Creating threads Controlling threads Thread states Summary
  • 4. Multithreading concepts Need for concurrency Multi processing Multi threading Multi threading makes user interfaces more responsive Multi threading makes better utilization of time when the program is blocking for IO
  • 5. 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 Pros and Cons Extending thread is simpler Implementing Runnable allows subclassing other classes
  • 6. Creating Threads – Extending Thread Extend java.lang.Thread Implement the run method See [SimpleThread.java]
  • 7. Creating Threads – Implementing Runnable Extend java.lang.Thread Implement the run mthod See [SimpleRunnable.java] A Runnable cannot throw a checked exception
  • 8. Thread Priorities Priorities are between 1 – 10 Best to use the constants defined in Thread MAX_PRIORITY MIN_PRIORITY NORM_PRIORITY Uses of thread priority
  • 9. States Of A Thread A thread can be in any one of these 4 states New: The thread object has been created but it has not been initialized Runnable: The thread object is ready to run whenever the CPU gives it a time slot Blocked: The thread could be run, but is currently not in a runnable state Dead: The thread has terminated
  • 10. Controlling Thread Behavior Yielding Sleeping Setting Priorities Joining
  • 11. Controlling Thread Behavior Yielding A thread can be made to yield when it comes to a point when the CPU can be relinquished to another thread Yielding is done by calling the yield() method A call to yield() is a hint to the underlying operating system. It does not guarantee that the CPU will be immediately given to another thread See [SimpleYieldingThread.java]
  • 12. Controlling Thread Behavior Sleeping A thread can be put to sleep for xxx ms Use the sleep(long x) call on the thread to put it to sleep for x ms The thread is guaranteed to sleep for x ms It may take more than that for the scheduler to give it control It may be interrupted by another thread See [SimpleThread.java]
  • 13. Controlling Thread Behavior Priorities Every thread can have a priority Scheduler will choose thread with highest priority for running first Exact mechanism of choosing the thread is indeterminate JDK supports 10 priority levels For portability it is best to use one of the predefined (MAX_PRIORITY, NORM_PRIORITY, MIN_PRIORITY) priority levels
  • 14. Controlling Thread Behavior Joining Another Thread Joining a thread is the process of suspending till the other thread completes execution Join can be called with or without a timeout Exercise SimpleJoiningThread.java
  • 15. Some Deprecated Methods Deprecated methods suspend & resume stop & destroy These methods are deadlock prone An alternate mechanism for stopping threads
  • 16. Sharing Resources In A Multithreaded Environment Multiple threads may try to access the same resource The point at which a thread will be suspended and another will resume is indeterminate A thread may not have finished totally processing a data structure before it is suspended. Another thread accessing the same data structure may find it in an improper state
  • 17. Controlling Access To Shared Resources Put the shared resource in an object Make all methods in the object which access the shared resource, synchronized Every object has a lock (monitor) Before a thread enters a synchronized method it must obtain the lock The lock is released when the thread leaves the synchronized method Only one thread can have a lock to an object at a time Synchronize a critical section on an object
  • 18. Atomic Operations Atomic operations are those operations that are guaranteed to be completed before a context switch Simple assignments and 'returning values' are some atomic operations An exception is when dealing with double and long values Be careful while omitting the synchronized keyword when multiple methods are accessing the shared resource
  • 19. Thread Blocking A thread can be blocked due to one of the following reasons It is waiting for I/O It has called its sleep(long ms) It has called the wait method The thread has called join on another thread The thread has called a synchronized method/block on another object and the lock is unavailable
  • 20. Using wait() and notify() with threads sleep(long ms) does not release the locks held by that thread Use wait() with notify() or notifyAll() instead See [WaitNotifyThread.java]
  • 21. Deadlock What is deadlock The dining philosophers problem Conditions for a deadlock to occur At least one resource used by threads is not shareable At least one thread holds a resource and is waiting on another resource which is being held by another thread A resource cannot be taken away from a thread A circular wait happens
  • 22. Threading In JDK 1.5 JDK 1.5 has increased support for threading Has a new concurrency packages java.util.concurrent java.util.concurrent.atomic java.util.concurrent.locks
  • 23. Summary It is important to understand when to use threads Caution must be exercised while writing multi-threaded code Thorough testing is recommended It is important to understand which classes and methods should be made thread safe
  • 24. Where to Get More Information Bruce Eckel's – Thinking In Java Taming Java Threads – Allen Holub