SlideShare ist ein Scribd-Unternehmen logo
1 von 14
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

Weitere ähnliche Inhalte

Was ist angesagt?

Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
myrajendra
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 

Was ist angesagt? (20)

Java Streams
Java StreamsJava Streams
Java Streams
 
Java program structure
Java program structureJava program structure
Java program structure
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java swing
Java swingJava swing
Java swing
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Java thread life cycle
Java thread life cycleJava thread life cycle
Java thread life cycle
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Features of java
Features of javaFeatures of java
Features of java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Operators in java
Operators in javaOperators in java
Operators in java
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 

Andere mochten auch (7)

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 

Ähnlich wie Threads in JAVA

07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
Java class 6
Java class 6Java class 6
Java class 6
Edureka!
 
Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
Health
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
HenryBriggs2
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 

Kürzlich hochgeladen (20)

Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stage
 
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Rums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfRums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdf
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 

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