SlideShare a Scribd company logo
Programming in Java
Topic: Multi-threading
Introduction
• Concurrent Execution of multiple tasks is called Multitasking.
Multitasking
Multi-processing Multi-threading
(Process-based) (Thread-based)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Introduction
• Multithreading is a specialized form of multitasking.
• A multithreaded program contains two or more parts (threads)
that can run concurrently.
• Each thread defines a separate path of execution.
• Java provides built-in support for multithreaded programming.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Process and Threads
• In concurrent programming, there are two basic units of execution:
processes and threads.
• Process: is an executable program loaded in memory
» has its own Variables & data structures (in memory)
» Communicate via operating system, files, network
» May contain multiple threads
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Threads
• A thread is an independent module of an application that can be
concurrently executed with other threads.
• Also known as “lightweight process”.
• Threads exist within a process — every process has at least one.
• Multiple threads in process execute same program.
• Threads share the process's resources, including memory and
open files.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• A thread cannot exist on its own; it must be a part of a process.
• A process remains running until all of the non-daemon threads
are done executing.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• Waiting/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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Multithreading in Java
• In order to achieve multithreading in java application,
java.lang.Runnable interface is provided.
• java.lang.Thread class is provided as part of core java library
which provides methods that are used to:
– start and suspend a thread
– obtain the state of a thread
– change the state of a thread
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Runnable Interface
• java.lang.Runnable interface provides the mechanism to
demarcate independent modules.
• Runnable interface contains a single method run().
public interface Runnable {
public void run();
}
• run() is executed by JVM as a thread.
• main() is also executed as a thread by JVM and is called main
thread.
• Main thread acts as the parent of all user threads.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Thread Class
• Thread class provides methods to start a thread, suspend a
thread and obtain the state of a thread.
public class Thread {
public Thread()
public Thread(String s)
public Thread(Runnable R); // Thread ⇒ R.run()
public Thread(Runnable R, String name);
public void start(); // begin thread execution
...
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of Thread class
• currentThread(): used to obtain the reference of thread
object for the current thread.
public static Thread currentThread()
• getName(): returns the name of the thread.
public String getName()
• setName(): used to change the name of a thread.
public void setName(String Name)
• getPriority(): used to obtain the priority of thread.
public int getPriority()
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of Thread class
• setPriority(): used to obtain the priority of thread.
public void setPriority(int p)
• start(): used to start the execution of a thread.
public void start()
• sleep(): is used to suspend the current thread for the specified time.
public static void sleep(long milliseconds) throws InterruptedException
• isAlive(): used to find out whether a thread is completed or not .
public boolean isAlive()
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Creating Threads in Java
• A user thread is represented by run().
• There are two ways of defining a thread:
– By extending Thread class
– By implementing Runnable interface
Runnable Runnable
Thread
MyThread MyThread
• The first case is not recommended because our class may already
have a super class, so we can not extend another class.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Implementing Runnable
• We can construct a thread on any object that implements Runnable.
• To implement Runnable, a class need only implement run( ).
• Inside run( ), we will define the code that constitutes the new thread.
• run( ) can call other methods, use other classes, and declare variables,
just like the main thread can.
• The only difference is that run( ) establishes the entry point for another,
concurrent thread of execution within our program.
• This thread will end when run( ) returns.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class MyThread implements Runnable
{
Thread t;
MyThread()
{
t = new Thread(this, "My Thread");
System.out.println("Child thread: " + t);
t.start();
}
public void run()
{
try {
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
} Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class ThreadDemo1
{
public static void main(String args[])
{
new MyThread();
try {
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)

More Related Content

What's hot

MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
myrajendra
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Lovely Professional University
 
Dot net assembly
Dot net assemblyDot net assembly
Dot net assembly
Dr.Neeraj Kumar Pandey
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
vanithaRamasamy
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
Nilesh Dalvi
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
Abhilash Nair
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
Java thread life cycle
Java thread life cycleJava thread life cycle
Java thread life cycle
Archana Gopinath
 
Files in java
Files in javaFiles in java
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
Multi threading
Multi threadingMulti threading
Multi threading
gndu
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 

What's hot (20)

MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Dot net assembly
Dot net assemblyDot net assembly
Dot net assembly
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
Interface in java
Interface in javaInterface in java
Interface in java
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Java thread life cycle
Java thread life cycleJava thread life cycle
Java thread life cycle
 
Files in java
Files in javaFiles in java
Files in java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 

Viewers also liked

Elcuerpohumano1
Elcuerpohumano1Elcuerpohumano1
Elcuerpohumano1
octubre11
 
threading and multi threading in java
threading and multi threading in javathreading and multi threading in java
threading and multi threading in java
Hamza Shah
 
09_Practical Multicore programming
09_Practical Multicore programming09_Practical Multicore programming
09_Practical Multicore programming
noerror
 
Design Pattern From Java To Ruby
Design Pattern From Java To RubyDesign Pattern From Java To Ruby
Design Pattern From Java To Ruby
yelogic
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
dheeraj_cse
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
choksheak
 
Packages in java
Packages in javaPackages in java
Packages in java
Abhishek Khune
 
Threads in java
Threads in javaThreads in java
Threads in java
mukesh singh
 
Design Pattern From Java To Ruby
Design Pattern    From Java To RubyDesign Pattern    From Java To Ruby
Design Pattern From Java To Ruby
Robbin Fan
 
Java packages
Java packagesJava packages
Java packages
Raja Sekhar
 

Viewers also liked (11)

Elcuerpohumano1
Elcuerpohumano1Elcuerpohumano1
Elcuerpohumano1
 
threading and multi threading in java
threading and multi threading in javathreading and multi threading in java
threading and multi threading in java
 
09_Practical Multicore programming
09_Practical Multicore programming09_Practical Multicore programming
09_Practical Multicore programming
 
Design Pattern From Java To Ruby
Design Pattern From Java To RubyDesign Pattern From Java To Ruby
Design Pattern From Java To Ruby
 
Java package
Java packageJava package
Java package
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Design Pattern From Java To Ruby
Design Pattern    From Java To RubyDesign Pattern    From Java To Ruby
Design Pattern From Java To Ruby
 
Java packages
Java packagesJava packages
Java packages
 

Similar to L22 multi-threading-introduction

Multi threading
Multi threadingMulti threading
Multi threading
Ravi Kant Sahu
 
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part IIPROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part II
SivaSankari36
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
madan r
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
Hemo Chella
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
TREXSHyNE
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Lovely Professional University
 
Lec 1.10 Object Oriented Programming
Lec 1.10 Object Oriented ProgrammingLec 1.10 Object Oriented Programming
Lec 1.10 Object Oriented Programming
Badar Waseer
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
ramyan49
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
Elizabeth alexander
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
Raheemaparveen
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
Himanshu Rajput
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
JanmejayaPadhiary2
 
Thread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using threadThread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using thread
poongothai11
 
Thread
ThreadThread
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
HarshaDokula
 
JAVA THEORY PPT.pptx on based up on the transaction
JAVA THEORY PPT.pptx on based up on the transactionJAVA THEORY PPT.pptx on based up on the transaction
JAVA THEORY PPT.pptx on based up on the transaction
SaikiranBiradar3
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
GouthamSoma1
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructors
Ravi_Kant_Sahu
 

Similar to L22 multi-threading-introduction (20)

Multi threading
Multi threadingMulti threading
Multi threading
 
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part IIPROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part II
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Lec 1.10 Object Oriented Programming
Lec 1.10 Object Oriented ProgrammingLec 1.10 Object Oriented Programming
Lec 1.10 Object Oriented Programming
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Thread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using threadThread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using thread
 
Thread
ThreadThread
Thread
 
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
 
JAVA THEORY PPT.pptx on based up on the transaction
JAVA THEORY PPT.pptx on based up on the transactionJAVA THEORY PPT.pptx on based up on the transaction
JAVA THEORY PPT.pptx on based up on the transaction
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructors
 

More from teach4uin

Controls
ControlsControls
Controls
teach4uin
 
validation
validationvalidation
validation
teach4uin
 
validation
validationvalidation
validation
teach4uin
 
Master pages
Master pagesMaster pages
Master pages
teach4uin
 
.Net framework
.Net framework.Net framework
.Net framework
teach4uin
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
teach4uin
 
Css1
Css1Css1
Css1
teach4uin
 
Code model
Code modelCode model
Code model
teach4uin
 
Asp db
Asp dbAsp db
Asp db
teach4uin
 
State management
State managementState management
State management
teach4uin
 
security configuration
security configurationsecurity configuration
security configuration
teach4uin
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tags
teach4uin
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tags
teach4uin
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
teach4uin
 
.Net overview
.Net overview.Net overview
.Net overview
teach4uin
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
teach4uin
 
enums
enumsenums
enums
teach4uin
 
memory
memorymemory
memory
teach4uin
 
array
arrayarray
array
teach4uin
 
storage clas
storage classtorage clas
storage clas
teach4uin
 

More from teach4uin (20)

Controls
ControlsControls
Controls
 
validation
validationvalidation
validation
 
validation
validationvalidation
validation
 
Master pages
Master pagesMaster pages
Master pages
 
.Net framework
.Net framework.Net framework
.Net framework
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
 
Css1
Css1Css1
Css1
 
Code model
Code modelCode model
Code model
 
Asp db
Asp dbAsp db
Asp db
 
State management
State managementState management
State management
 
security configuration
security configurationsecurity configuration
security configuration
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tags
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tags
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
 
.Net overview
.Net overview.Net overview
.Net overview
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
 
enums
enumsenums
enums
 
memory
memorymemory
memory
 
array
arrayarray
array
 
storage clas
storage classtorage clas
storage clas
 

Recently uploaded

Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 

Recently uploaded (20)

Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 

L22 multi-threading-introduction

  • 1. Programming in Java Topic: Multi-threading
  • 2. Introduction • Concurrent Execution of multiple tasks is called Multitasking. Multitasking Multi-processing Multi-threading (Process-based) (Thread-based) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 3. Introduction • Multithreading is a specialized form of multitasking. • A multithreaded program contains two or more parts (threads) that can run concurrently. • Each thread defines a separate path of execution. • Java provides built-in support for multithreaded programming. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4. Process and Threads • In concurrent programming, there are two basic units of execution: processes and threads. • Process: is an executable program loaded in memory » has its own Variables & data structures (in memory) » Communicate via operating system, files, network » May contain multiple threads Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5. Threads • A thread is an independent module of an application that can be concurrently executed with other threads. • Also known as “lightweight process”. • Threads exist within a process — every process has at least one. • Multiple threads in process execute same program. • Threads share the process's resources, including memory and open files. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6. • A thread cannot exist on its own; it must be a part of a process. • A process remains running until all of the non-daemon threads are done executing. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 7. 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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 8. • Waiting/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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 9. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 10. Multithreading in Java • In order to achieve multithreading in java application, java.lang.Runnable interface is provided. • java.lang.Thread class is provided as part of core java library which provides methods that are used to: – start and suspend a thread – obtain the state of a thread – change the state of a thread Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11. Runnable Interface • java.lang.Runnable interface provides the mechanism to demarcate independent modules. • Runnable interface contains a single method run(). public interface Runnable { public void run(); } • run() is executed by JVM as a thread. • main() is also executed as a thread by JVM and is called main thread. • Main thread acts as the parent of all user threads. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 12. Thread Class • Thread class provides methods to start a thread, suspend a thread and obtain the state of a thread. public class Thread { public Thread() public Thread(String s) public Thread(Runnable R); // Thread ⇒ R.run() public Thread(Runnable R, String name); public void start(); // begin thread execution ... } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13. Methods of Thread class • currentThread(): used to obtain the reference of thread object for the current thread. public static Thread currentThread() • getName(): returns the name of the thread. public String getName() • setName(): used to change the name of a thread. public void setName(String Name) • getPriority(): used to obtain the priority of thread. public int getPriority() Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 14. Methods of Thread class • setPriority(): used to obtain the priority of thread. public void setPriority(int p) • start(): used to start the execution of a thread. public void start() • sleep(): is used to suspend the current thread for the specified time. public static void sleep(long milliseconds) throws InterruptedException • isAlive(): used to find out whether a thread is completed or not . public boolean isAlive() Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 15. Creating Threads in Java • A user thread is represented by run(). • There are two ways of defining a thread: – By extending Thread class – By implementing Runnable interface Runnable Runnable Thread MyThread MyThread • The first case is not recommended because our class may already have a super class, so we can not extend another class. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 16. Implementing Runnable • We can construct a thread on any object that implements Runnable. • To implement Runnable, a class need only implement run( ). • Inside run( ), we will define the code that constitutes the new thread. • run( ) can call other methods, use other classes, and declare variables, just like the main thread can. • The only difference is that run( ) establishes the entry point for another, concurrent thread of execution within our program. • This thread will end when run( ) returns. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 17. class MyThread implements Runnable { Thread t; MyThread() { t = new Thread(this, "My Thread"); System.out.println("Child thread: " + t); t.start(); } public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18. class ThreadDemo1 { public static void main(String args[]) { new MyThread(); try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)