SlideShare a Scribd company logo
Multithreading
Threads
• Threads are lightweight processes as the
overhead of switching between threads is less
• The can be easily spawned
• The Java Virtual Machine spawns a thread
when your program is run called the Main
Thread
Why do we need threads?
• To enhance parallel processing
• To increase response to the user
• To utilize the idle time of the CPU
• Prioritize your work depending on priority
Example
• Consider a simple web server
• The web server listens for request and serves it
• If the web server was not multithreaded, the
requests processing would be in a queue, thus
increasing the response time and also might hang
the server if there was a bad request.
• By implementing in a multithreaded
environment, the web server can serve multiple
request simultaneously thus improving response
time
Creating threads
• In java threads can be created by extending
the Thread class or implementing the
Runnable Interface
• It is more preferred to implement the
Runnable Interface so that we can extend
properties from other classes
• Implement the run() method which is the
starting point for thread execution
Running threads
• Example
class mythread implements Runnable{
public void run(){
System.out.println(“Thread Started”);
}
}
class mainclass {
public static void main(String args[]){
Thread t = new Thread(new mythread()); // This is the way to instantiate a
thread implementing runnable interface
t.start(); // starts the thread by running the run method
}
}
• Calling t.run() does not start a thread, it is just a simple
method call.
• Creating an object does not create a thread, calling
start() method creates the thread.
Synchronization
• Synchronization is prevent data corruption
• Synchronization allows only one thread to
perform an operation on a object at a time.
• If multiple threads require an access to an
object, synchronization helps in maintaining
consistency.
Example
public class Counter{
private int count = 0;
public int getCount(){
return count;
}
public setCount(int count){
this.count = count;
}
}
• In this example, the counter tells how many an access has been made.
• If a thread is accessing setCount and updating count and another thread is accessing
getCount at the same time, there will be inconsistency in the value of count.
Fixing the example
public class Counter{
private static int count = 0;
public synchronized int getCount(){
return count;
}
public synchoronized setCount(int count){
this.count = count;
}
}
• By adding the synchronized keyword we make sure that when one thread is in the setCount
method the other threads are all in waiting state.
• The synchronized keyword places a lock on the object, and hence locks all the other methods
which have the keyword synchronized. The lock does not lock the methods without the
keyword synchronized and hence they are open to access by other threads.
What about static methods?
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}
public static synchronized setCount(int count){
this.count = count;
}
}
• In this example the methods are static and hence are associated with the class object and not
the instance.
• Hence the lock is placed on the class object that is, Counter.class object and not on the
object itself. Any other non static synchronized methods are still available for access by
other threads.
Common Synchronization mistake
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}
public synchronized setCount(int count){
this.count = count;
}
}
• The common mistake here is one method is static synchronized and another method is non
static synchronized.
• This makes a difference as locks are placed on two different objects. The class object and the
instance and hence two different threads can access the methods simultaneously.
Object locking
• The object can be explicitly locked in this way
synchronized(myInstance){
try{
wait();
}catch(InterruptedException ex){
}
System.out.println(“Iam in this “);
notifyAll();
}
• The synchronized keyword locks the object. The wait keyword waits
for the lock to be acquired, if the object was already locked by
another thread. Notifyall() notifies other threads that the lock is about
to be released by the current thread.
• Another method notify() is available for use, which wakes up only the
next thread which is in queue for the object, notifyall() wakes up all
the threads and transfers the lock to another thread having the
highest priority.
Further Reading
• http://docs.oracle.com/javase/tutorial/essenti
al/concurrency/sync.html
• http://javarevisited.blogspot.com/2011/04/
synchronization-in-java-synchronized.html

More Related Content

Similar to Multithreading in java programming language.ppt (20)

PPTX
unit-3java.pptx
sujatha629799
 
PPTX
Chap3 multi threaded programming
raksharao
 
PPTX
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
jakjak36
 
PPTX
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
PPTX
advanced java ppt
PreetiDixit22
 
PPTX
84694646456445645645645665656465464sdd.pptx
mhp821023
 
PPT
Md09 multithreading
Rakesh Madugula
 
PPTX
Multithreading
sagsharma
 
PPTX
multithreading.pptx
Sravanibitragunta
 
PPTX
Java programming PPT. .pptx
creativegamerz00
 
PPTX
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
 
PPTX
Multi-threaded Programming in JAVA
Vikram Kalyani
 
PDF
Threads
saanchi85
 
PPT
Multithreading
backdoor
 
PDF
Multithreading-in app app-Java.pdf (1).pdf
jaijsr12345
 
PPT
Programming - Java-Threads-and-Synchronization.ppt
smychung
 
PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
KusumitaSahoo1
 
PPTX
U4 JAVA.pptx
madan r
 
PPT
Java concurrency
ducquoc_vn
 
PDF
Java Multithreading Interview Questions PDF By ScholarHat
Scholarhat
 
unit-3java.pptx
sujatha629799
 
Chap3 multi threaded programming
raksharao
 
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
jakjak36
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
advanced java ppt
PreetiDixit22
 
84694646456445645645645665656465464sdd.pptx
mhp821023
 
Md09 multithreading
Rakesh Madugula
 
Multithreading
sagsharma
 
multithreading.pptx
Sravanibitragunta
 
Java programming PPT. .pptx
creativegamerz00
 
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
 
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Threads
saanchi85
 
Multithreading
backdoor
 
Multithreading-in app app-Java.pdf (1).pdf
jaijsr12345
 
Programming - Java-Threads-and-Synchronization.ppt
smychung
 
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
KusumitaSahoo1
 
U4 JAVA.pptx
madan r
 
Java concurrency
ducquoc_vn
 
Java Multithreading Interview Questions PDF By ScholarHat
Scholarhat
 

Recently uploaded (20)

PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Python basic programing language for automation
DanialHabibi2
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Ad

Multithreading in java programming language.ppt

  • 2. Threads • Threads are lightweight processes as the overhead of switching between threads is less • The can be easily spawned • The Java Virtual Machine spawns a thread when your program is run called the Main Thread
  • 3. Why do we need threads? • To enhance parallel processing • To increase response to the user • To utilize the idle time of the CPU • Prioritize your work depending on priority
  • 4. Example • Consider a simple web server • The web server listens for request and serves it • If the web server was not multithreaded, the requests processing would be in a queue, thus increasing the response time and also might hang the server if there was a bad request. • By implementing in a multithreaded environment, the web server can serve multiple request simultaneously thus improving response time
  • 5. Creating threads • In java threads can be created by extending the Thread class or implementing the Runnable Interface • It is more preferred to implement the Runnable Interface so that we can extend properties from other classes • Implement the run() method which is the starting point for thread execution
  • 6. Running threads • Example class mythread implements Runnable{ public void run(){ System.out.println(“Thread Started”); } } class mainclass { public static void main(String args[]){ Thread t = new Thread(new mythread()); // This is the way to instantiate a thread implementing runnable interface t.start(); // starts the thread by running the run method } } • Calling t.run() does not start a thread, it is just a simple method call. • Creating an object does not create a thread, calling start() method creates the thread.
  • 7. Synchronization • Synchronization is prevent data corruption • Synchronization allows only one thread to perform an operation on a object at a time. • If multiple threads require an access to an object, synchronization helps in maintaining consistency.
  • 8. Example public class Counter{ private int count = 0; public int getCount(){ return count; } public setCount(int count){ this.count = count; } } • In this example, the counter tells how many an access has been made. • If a thread is accessing setCount and updating count and another thread is accessing getCount at the same time, there will be inconsistency in the value of count.
  • 9. Fixing the example public class Counter{ private static int count = 0; public synchronized int getCount(){ return count; } public synchoronized setCount(int count){ this.count = count; } } • By adding the synchronized keyword we make sure that when one thread is in the setCount method the other threads are all in waiting state. • The synchronized keyword places a lock on the object, and hence locks all the other methods which have the keyword synchronized. The lock does not lock the methods without the keyword synchronized and hence they are open to access by other threads.
  • 10. What about static methods? public class Counter{ private int count = 0; public static synchronized int getCount(){ return count; } public static synchronized setCount(int count){ this.count = count; } } • In this example the methods are static and hence are associated with the class object and not the instance. • Hence the lock is placed on the class object that is, Counter.class object and not on the object itself. Any other non static synchronized methods are still available for access by other threads.
  • 11. Common Synchronization mistake public class Counter{ private int count = 0; public static synchronized int getCount(){ return count; } public synchronized setCount(int count){ this.count = count; } } • The common mistake here is one method is static synchronized and another method is non static synchronized. • This makes a difference as locks are placed on two different objects. The class object and the instance and hence two different threads can access the methods simultaneously.
  • 12. Object locking • The object can be explicitly locked in this way synchronized(myInstance){ try{ wait(); }catch(InterruptedException ex){ } System.out.println(“Iam in this “); notifyAll(); } • The synchronized keyword locks the object. The wait keyword waits for the lock to be acquired, if the object was already locked by another thread. Notifyall() notifies other threads that the lock is about to be released by the current thread. • Another method notify() is available for use, which wakes up only the next thread which is in queue for the object, notifyall() wakes up all the threads and transfers the lock to another thread having the highest priority.
  • 13. Further Reading • http://docs.oracle.com/javase/tutorial/essenti al/concurrency/sync.html • http://javarevisited.blogspot.com/2011/04/ synchronization-in-java-synchronized.html