SlideShare una empresa de Scribd logo
1 de 14
Descargar para leer sin conexión
Threads : Java
Prepared By Tuhin Kundu
What is a Thread?
facility to allow multiple activities to coexist within a
single process.
Represents a separate path of execution of a group of
statements
Java is the first language to include threading within the
language, rather than treating it as a facility of the OS
 Video Game example
1.one thread for graphics
2.one thread for user interaction
3.one thread for networking
 Server Example
1.Do various jobs
2.Handle Several Clients
Main Thread
Default Thread in any Java Program
JVM uses to execute program statements
o Program To Find the Main Thread
Class Current
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println(“Current Thread: “+t);
System.out.println(“Name is: “+t.getName());
}
}
Threads in Java
Creating threads in Java:
Extend java.lang.Thread class
run() method must be overridden (similar to main method
of sequential program)
run() is called when execution of the thread begins
A thread terminates when run() returns
start() method invokes run()
OR
Implement java.lang.Runnable interface
4
Life cycle of a Thread
 New
The thread is in new state if you create an instance
of Thread class but before the invocation of start()
method.
 Runnable
The thread is in runnable state after invocation of start() method,
but the thread scheduler has not selected it to be the running
thread.
 Running
The thread is in running state if the thread scheduler has
selected it.
 Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not
eligible to run.
 Terminated
A thread is in terminated or dead state when its run() method
exits.
Thread Priority
 Each thread is assigned a default priority of
Thread.NORM_PRIORITY (constant of 5).
 You can reset the priority using setPriority(int priority).
 Some constants for priorities include:
o Thread.MIN_PRIORITY
o Thread.MAX_PRIORITY
o Thread.NORM_PRIORITY
 By default, a thread has the priority level of the thread that
created it.
7
 Thread Synchronization8
A shared resource may be corrupted if it is accessed
simultaneously by multiple threads.
Example: two unsynchronized threads accessing the same
bank account may cause conflict.
 Known as a race condition in multithreaded programs.
A thread-safe class does not cause a race condition in the
presence of multiple threads.
Synchronized
Problem : race conditions
Solution : give exclusive access to one thread at a time to code
that manipulates a shared object.
Synchronization keeps other threads waiting until the object is
available.
The synchronized keyword synchronizes the method so that only one
thread can access the method at a time.
public synchronized void xMethod() {
// method body
}
Obj t1 ( Enters the object )
t2—wait until t1 comes out
9
Deadlock :
a part of multithreading
can occur when a thread is waiting for an object lock, that
is acquired by another thread and second thread is waiting
for an object lock that is acquired by first thread
Since, both threads are waiting for each other to release
the lock, the condition is called deadlock
Preventing Deadlock
Deadlock can be easily avoided by resource ordering.
With this technique, assign an order on all the objects
whose locks must be acquired and ensure that the
locks are acquired in that order.
Example:
Thread 1:
lock A lock B
Thread 2:
wait for A lock C(when A is locked)
Thread 3:
wait for A wait for B wait for C
11
Advantages of Threads:
easier to program
provide better performance
allow any program to perform multiple tasks at once.
multiple threads can share resources
an Internet-aware language such as Java, this is a very
important tool
References
 http://www.slideshare.net/parag/multithreading-in-java
 https://code.google.com/p/googleappengine/wiki/SdkForJavaReleaseNotes
 http://stackoverflow.com/questions/2213340/what-is-daemon-thread-in-java
 https://github.com/orientechnologies/orientdb/wiki/Java-Multi-Threading
 http://www.javatpoint.com/creating-thread
 http://www.tutorialspoint.com/java/java_multithreading.htm
 http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html
 http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
 http://www.javabeginner.com/learn-java/java-threads-tutorial
 http://www.geeksforgeeks.org/java/
 http://www.javacodegeeks.com/2014/08/java-concurrency-tutorial-visibility-between-
threads.html
End of Module
Thank You

Más contenido relacionado

La actualidad más candente

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-threadjavaicon
 
Java package
Java packageJava package
Java packageCS_GDRCST
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationHoneyChintal
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 

La actualidad más candente (20)

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Applets
AppletsApplets
Applets
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
 
Java package
Java packageJava package
Java package
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java string handling
Java string handlingJava string handling
Java string handling
 
OOP java
OOP javaOOP java
OOP java
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Similar a Threads in JAVA

Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
Java class 6
Java class 6Java class 6
Java class 6Edureka!
 
Multithreading
MultithreadingMultithreading
Multithreadingbackdoor
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in javaDucat India
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 

Similar a Threads in JAVA (20)

Java Threads
Java ThreadsJava Threads
Java Threads
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
java_threads.ppt
java_threads.pptjava_threads.ppt
java_threads.ppt
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Java class 6
Java class 6Java class 6
Java class 6
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in java
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Java
JavaJava
Java
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 

Último

Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxPoonam60376
 
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...arifengg7
 
Guardians of E-Commerce: Harnessing NLP and Machine Learning Approaches for A...
Guardians of E-Commerce: Harnessing NLP and Machine Learning Approaches for A...Guardians of E-Commerce: Harnessing NLP and Machine Learning Approaches for A...
Guardians of E-Commerce: Harnessing NLP and Machine Learning Approaches for A...IJAEMSJORNAL
 
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxTriangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxRomil Mishra
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.elesangwon
 
A brief look at visionOS - How to develop app on Apple's Vision Pro
A brief look at visionOS - How to develop app on Apple's Vision ProA brief look at visionOS - How to develop app on Apple's Vision Pro
A brief look at visionOS - How to develop app on Apple's Vision ProRay Yuan Liu
 
Submerged Combustion, Explosion Flame Combustion, Pulsating Combustion, and E...
Submerged Combustion, Explosion Flame Combustion, Pulsating Combustion, and E...Submerged Combustion, Explosion Flame Combustion, Pulsating Combustion, and E...
Submerged Combustion, Explosion Flame Combustion, Pulsating Combustion, and E...Ayisha586983
 
1- Practice occupational health and safety procedures.pptx
1- Practice occupational health and safety procedures.pptx1- Practice occupational health and safety procedures.pptx
1- Practice occupational health and safety procedures.pptxMel Paras
 
Uk-NO1 kala jadu karne wale ka contact number kala jadu karne wale baba kala ...
Uk-NO1 kala jadu karne wale ka contact number kala jadu karne wale baba kala ...Uk-NO1 kala jadu karne wale ka contact number kala jadu karne wale baba kala ...
Uk-NO1 kala jadu karne wale ka contact number kala jadu karne wale baba kala ...Amil baba
 
ADM100 Running Book for sap basis domain study
ADM100 Running Book for sap basis domain studyADM100 Running Book for sap basis domain study
ADM100 Running Book for sap basis domain studydhruvamdhruvil123
 
70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical trainingGladiatorsKasper
 
10 AsymmetricKey Cryptography students.pptx
10 AsymmetricKey Cryptography students.pptx10 AsymmetricKey Cryptography students.pptx
10 AsymmetricKey Cryptography students.pptxAdityaGoogle
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSneha Padhiar
 
Prach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism CommunityPrach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism Communityprachaibot
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxStephen Sitton
 
Curve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptxCurve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptxRomil Mishra
 
Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...
Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...
Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...Amil baba
 
Artificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewArtificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewsandhya757531
 
Substation Automation SCADA and Gateway Solutions by BRH
Substation Automation SCADA and Gateway Solutions by BRHSubstation Automation SCADA and Gateway Solutions by BRH
Substation Automation SCADA and Gateway Solutions by BRHbirinder2
 

Último (20)

Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
 
Guardians of E-Commerce: Harnessing NLP and Machine Learning Approaches for A...
Guardians of E-Commerce: Harnessing NLP and Machine Learning Approaches for A...Guardians of E-Commerce: Harnessing NLP and Machine Learning Approaches for A...
Guardians of E-Commerce: Harnessing NLP and Machine Learning Approaches for A...
 
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxTriangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
 
Versatile Engineering Construction Firms
Versatile Engineering Construction FirmsVersatile Engineering Construction Firms
Versatile Engineering Construction Firms
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
 
A brief look at visionOS - How to develop app on Apple's Vision Pro
A brief look at visionOS - How to develop app on Apple's Vision ProA brief look at visionOS - How to develop app on Apple's Vision Pro
A brief look at visionOS - How to develop app on Apple's Vision Pro
 
Submerged Combustion, Explosion Flame Combustion, Pulsating Combustion, and E...
Submerged Combustion, Explosion Flame Combustion, Pulsating Combustion, and E...Submerged Combustion, Explosion Flame Combustion, Pulsating Combustion, and E...
Submerged Combustion, Explosion Flame Combustion, Pulsating Combustion, and E...
 
1- Practice occupational health and safety procedures.pptx
1- Practice occupational health and safety procedures.pptx1- Practice occupational health and safety procedures.pptx
1- Practice occupational health and safety procedures.pptx
 
Uk-NO1 kala jadu karne wale ka contact number kala jadu karne wale baba kala ...
Uk-NO1 kala jadu karne wale ka contact number kala jadu karne wale baba kala ...Uk-NO1 kala jadu karne wale ka contact number kala jadu karne wale baba kala ...
Uk-NO1 kala jadu karne wale ka contact number kala jadu karne wale baba kala ...
 
ADM100 Running Book for sap basis domain study
ADM100 Running Book for sap basis domain studyADM100 Running Book for sap basis domain study
ADM100 Running Book for sap basis domain study
 
70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training
 
10 AsymmetricKey Cryptography students.pptx
10 AsymmetricKey Cryptography students.pptx10 AsymmetricKey Cryptography students.pptx
10 AsymmetricKey Cryptography students.pptx
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
 
Prach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism CommunityPrach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism Community
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptx
 
Curve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptxCurve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptx
 
Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...
Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...
Uk-NO1 Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Exp...
 
Artificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewArtificial Intelligence in Power System overview
Artificial Intelligence in Power System overview
 
Substation Automation SCADA and Gateway Solutions by BRH
Substation Automation SCADA and Gateway Solutions by BRHSubstation Automation SCADA and Gateway Solutions by BRH
Substation Automation SCADA and Gateway Solutions by BRH
 

Threads in JAVA

  • 1. Threads : Java Prepared By Tuhin Kundu
  • 2. What is a Thread? facility to allow multiple activities to coexist within a single process. Represents a separate path of execution of a group of statements Java is the first language to include threading within the language, rather than treating it as a facility of the OS  Video Game example 1.one thread for graphics 2.one thread for user interaction 3.one thread for networking  Server Example 1.Do various jobs 2.Handle Several Clients
  • 3. Main Thread Default Thread in any Java Program JVM uses to execute program statements o Program To Find the Main Thread Class Current { public static void main(String args[]) { Thread t=Thread.currentThread(); System.out.println(“Current Thread: “+t); System.out.println(“Name is: “+t.getName()); } }
  • 4. Threads in Java Creating threads in Java: Extend java.lang.Thread class run() method must be overridden (similar to main method of sequential program) run() is called when execution of the thread begins A thread terminates when run() returns start() method invokes run() OR Implement java.lang.Runnable interface 4
  • 5. Life cycle of a Thread
  • 6.  New The thread is in new state if you create an instance of Thread class but before the invocation of start() method.  Runnable The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.  Running The thread is in running state if the thread scheduler has selected it.  Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently not eligible to run.  Terminated A thread is in terminated or dead state when its run() method exits.
  • 7. Thread Priority  Each thread is assigned a default priority of Thread.NORM_PRIORITY (constant of 5).  You can reset the priority using setPriority(int priority).  Some constants for priorities include: o Thread.MIN_PRIORITY o Thread.MAX_PRIORITY o Thread.NORM_PRIORITY  By default, a thread has the priority level of the thread that created it. 7
  • 8.  Thread Synchronization8 A shared resource may be corrupted if it is accessed simultaneously by multiple threads. Example: two unsynchronized threads accessing the same bank account may cause conflict.  Known as a race condition in multithreaded programs. A thread-safe class does not cause a race condition in the presence of multiple threads.
  • 9. Synchronized Problem : race conditions Solution : give exclusive access to one thread at a time to code that manipulates a shared object. Synchronization keeps other threads waiting until the object is available. The synchronized keyword synchronizes the method so that only one thread can access the method at a time. public synchronized void xMethod() { // method body } Obj t1 ( Enters the object ) t2—wait until t1 comes out 9
  • 10. Deadlock : a part of multithreading can occur when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread Since, both threads are waiting for each other to release the lock, the condition is called deadlock
  • 11. Preventing Deadlock Deadlock can be easily avoided by resource ordering. With this technique, assign an order on all the objects whose locks must be acquired and ensure that the locks are acquired in that order. Example: Thread 1: lock A lock B Thread 2: wait for A lock C(when A is locked) Thread 3: wait for A wait for B wait for C 11
  • 12. Advantages of Threads: easier to program provide better performance allow any program to perform multiple tasks at once. multiple threads can share resources an Internet-aware language such as Java, this is a very important tool
  • 13. References  http://www.slideshare.net/parag/multithreading-in-java  https://code.google.com/p/googleappengine/wiki/SdkForJavaReleaseNotes  http://stackoverflow.com/questions/2213340/what-is-daemon-thread-in-java  https://github.com/orientechnologies/orientdb/wiki/Java-Multi-Threading  http://www.javatpoint.com/creating-thread  http://www.tutorialspoint.com/java/java_multithreading.htm  http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html  http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html  http://www.javabeginner.com/learn-java/java-threads-tutorial  http://www.geeksforgeeks.org/java/  http://www.javacodegeeks.com/2014/08/java-concurrency-tutorial-visibility-between- threads.html