SlideShare a Scribd company logo
Multithreading Programming in Java
Elizabeth Alexander
Hindustan University
Multithreading
● Multithreading is a Java feature that allows concurrent execution of two or more
parts of a program for maximum utilization of CPU.
● Each part of such program is called a thread.
● Thread is basically a lightweight sub-process within a process ie, a smallest unit of
processing.
● Multithreading is are used to achieve multitasking.
● In multithreading ,threads share a common memory area. They don't allocate
separate memory area so saves memory, and context-switching between the
threads takes less time than process.
● Java Multithreading is mostly used in games, animation etc.
Multithreading Cont...
● Multithreading is best in all cases in contrast with single-thread model.
● Single-thread system uses an approach of event loop with polling.
● A single thread in the system runs in an infinite loop.
● Polling the mechanism, that selects a single event from the event queue to
choose what to do next. As the event is selected, then event loop forwards the
control to the corresponding required event handler. Nothing else can be
happened, until the event handler returns.
● Because of this CPU time is wasted.
● Here, only one part of the complete program is dominating the whole system, and
preventing the system to execute or start any other process.
● In single-thread model one thread blocks all other threads until its execution
completes.
Multithreading Cont...
● On other waiting or idle thread can start and acquire the resource which is not in
use by the current thread. This causes the wastage of resources.
● Java's multithreading provides benefit in this area by eliminating the loop and
polling mechanism, one thread can be paused without stopping the other parts of
the program. If any thread is paused or blocked, still other threads continue to run.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can
perform multiple operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in
a single thread.
Thread in java
● A thread is a lightweight sub process, a smallest unit of processing. It is a
separate path of execution.
● Threads are independent, if there occurs exception in one thread, it doesn't affect
other threads. It shares a common memory area.
The Java Thread Model(Thread Life Cycle)
The Java Thread Model Cont...
New/Ready to run
● A new thread begins its life cycle in the new state.
● First time as soon as it gets CPU time.
● It remains in this state until the program starts the thread. It is also referred to
as a born thread.
Runnable
● Under execution.
● After a newly born thread is started, the thread becomes runnable.
● A thread in this state is considered to be executing its task.
The Java Thread Model Cont...
Waiting/Suspended
● Temporarily not active or under execution.
● Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task.
● A thread transitions back to the runnable state only when another thread
signals the waiting thread to continue executing.
Timed Waiting
● A runnable thread can enter the timed waiting state for a specified interval of
time.
● A thread in this state transitions back to the runnable state when that time
interval expires or when the event it is waiting for occurs.
The Java Thread Model Cont...
Blocked
● Waiting for resources.
Resumed
● Suspended thread resumed, and start from where it left off.
Terminated (Dead)
● Halts the execution immediately and never resumes.
● A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
The Java Thread Model Cont...
Main thread in Java
● When a Java program starts up, one thread begins running immediately. This is
usually called the main thread of our program, because it is the one that is
executed when our program begins.
Properties :
● It is the parent of all the threads of the program and all other "child" threads will be
spawned from it.
● It must be the last thread to finish execution because it performs various
shutdown actions
How to control Main thread
● The main thread is created automatically when our program is started.
● To control it we must obtain a reference to the main thread.
● This can be done by calling a static method currentThread( ) which is present in
Thread class.
Main thread in Java
● Its general form is static Thread currentThread( )
● This method returns a reference to the thread on which it is called.
● The default priority of Main thread is 5 and for all remaining user threads priority
will be inherited from parent to child.
Flow Diagram of Main Thread
Creating a thread
● Java defines two ways by which a thread can be created.
○ By implementing the Runnable interface.
○ By extending the Thread class.
Thread class:
● Thread class provide constructors and methods to create and perform operations
on a thread.
● Thread class extends Object class and implements Runnable interface.
● The Object class is the parent class of all the classes in java by default. In other
words, it is the topmost class of java.
Commonly used Constructors of Thread class:
● Thread()
● Thread(String name)
● Thread(Runnable r)
● Thread(Runnable r,String name)
Create a Thread by Extending a Thread Class
● The first way to create a thread is to create a new class that extends Thread
class.
● This approach provides more flexibility in handling multiple threads created using
available methods in Thread class.
Step 1
● You will need to override run( ) method available in Thread class.
● You must specify the code that your thread will execute inside run() method.
● Syntax of run() method − public void run( )
Step 2
● Once Thread object is created, you can start it by calling start() method, which
executes a call to run( ) method.
● Syntax of start() method − void start( );
Create a Thread by Implementing a Runnable Interface
● The easiest way to create a thread is to create a class that implements the
runnable interface
● If your class is intended to be executed as a thread then you can achieve this by
implementing a Runnable interface.
Step 1
● You need to implement a run() method provided by a Runnable interface.
● This method provides an entry point for the thread a
● You must specify the code that your thread will execute inside run() method.
● Syntax of the run() method − public void run( )
● run() method can call other methods, can use other classes and declare variables
just like any other normal method.
Step 2
● As a second step, you will instantiate a Thread object using the following
constructor − Thread(Runnable threadObj, String threadName);
● Where, threadObj is an instance of a class that implements the
Runnableinterface and threadName is the name given to the new thread.
Step 3
● Once a Thread object is created, you can start it by calling start() method, which
executes a call to run( ) method.
● Syntax of start() method − void start();
Thread Priorities
● In a Multi threading environment, thread scheduler assigns processor to a thread
based on priority of thread.
● Whenever we create a thread in Java, it always has some priority assigned to it.
● Priority can either be given by JVM while creating the thread or it can be given by
programmer explicitly.
● Accepted value of priority for a thread is in range of 1 to 10.
● There are 3 static variables defined in Thread class for priority.
○ public static int MIN_PRIORITY: This is minimum priority that a thread can
have. Value for this is 1.
○ public static int NORM_PRIORITY: This is default priority of a thread if do
not explicitly define it. Value for this is 5.
○ public static int MAX_PRIORITY: This is maximum priority of a thread.
Value for this is 10.
Thread Priorities Cont...
Get and Set Thread Priority:
● public final int getPriority(): java.lang.Thread.getPriority() method returns
priority of given thread.
● public final void setPriority(int newPriority): java.lang.Thread.setPriority()
method changes the priority of thread to the value newPriority.
○ This method throws IllegalArgumentException if value of parameter
newPriority goes beyond minimum(1) and maximum(10) limit.
Note:
● Thread with highest priority will get execution chance prior to other threads.
Suppose there are 3 threads t1, t2 and t3 with priorities 4, 6 and 1. So, thread t2
will execute first based on maximum priority 6 after that t1 will execute and then
t3.
● Default priority for main thread is always 5, it can be changed later. Default priority
for all other threads depends on the priority of parent thread.
Synchronization in Java
● Multi-threaded programs may often come to a situation where multiple threads try
to access the same resources and finally produce erroneous results.
● For example, if multiple threads try to write within a same file then they may
corrupt the data because one of the threads can override data or while one thread
is opening the same file at the same time another thread might be closing the
same file.
● So it needs to be made sure by some synchronization method that only one
thread can access the resource at a given point of time.This is implemented using
a concept called monitors.
● Each object in Java is associated with a monitor, which a thread can lock or
unlock. Only one thread at a time may hold a lock on a monitor.
Synchronization in Java Cont...
● Java programming language provides a way of creating threads and
synchronizing their task by using synchronized blocks. We keep shared
resources within this block.
● Synchronized blocks in Java are marked with the synchronized keyword.
● All synchronized blocks synchronized on the same object can only have one
thread executing inside them at a time.
● All other threads attempting to enter the synchronized block are blocked until the
thread inside the synchronized block exits the block.
● General form of a synchronized block:
synchronized(sync_object)
{
// Access shared variables and other
// shared resources
}
Synchronization in Java Cont...
● Here, the sync_object is a reference to an object whose lock associates with the
monitor that the synchronized statement represents.
● Synchronization in java is the capability to control the access of multiple threads
to any shared resource.
● Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Why use Synchronization
● The synchronization is mainly used to
■ To prevent thread interference.:Interference occurs when two
operations , running in different threads , but acting on the same data
■ To prevent consistency problem. : Consistency Errors occurs when
different threads have inconsistent views of the shared data.
Inter-thread communication in Java
● Inter-thread communication or Co-operation is about allowing synchronized
threads to communicate with each other.
● In concurrent programming, concurrent accesses to shared resources can lead to
unexpected or erroneous behavior, so parts of the program where the shared
resource is accessed are protected. This protected section is the critical section
or critical region
● Inter-thread communication is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the
same critical section to be executed.
● Java uses Inter-thread communication or Co-operation to avoid polling.
○ The process of testing a condition repeatedly till it becomes true is known as
polling.
Inter-thread communication in Java Cont...
● Polling is usually implemented with the help of loops to check whether a particular
condition is true or not. If it is true, certain action is taken. This waste many CPU
cycles and makes the implementation inefficient.
● Inter-thread communication is implemented by following methods of Object
class:
■ wait()
■ notify()
■ notifyAll()
wait() method
● Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
notify() method
● Wakes up a single thread that is waiting on this object's monitor. If any threads
are waiting on this object, one of them is chosen to be awakened. The choice is
arbitrary.
■ Syntax: public final void notify()
notifyAll() method
● Wakes up all threads that are waiting on this object's monitor.
■ Syntax: public final void notifyAll()
Multithreading programming in java
Concept of Lock in Java
● Synchronization is built around an internal entity known as the lock or
monitor.
● Every object has a lock associated with it.
● By convention, a thread that needs consistent access to an object's fields has
to acquire the object's lock before accessing them, and then release the lock
when it's done with them.
Deadlock in java
● Deadlock in java is a part of multithreading. Deadlock can occur in a situation
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.
Multithreading programming in java

More Related Content

What's hot (20)

Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
Ashok Raj
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
Shiv Mehmi
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
Event handling
Event handlingEvent handling
Event handling
swapnac12
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
Medhat Dawoud
 
Introduction to package in java
Introduction to package in javaIntroduction to package in java
Introduction to package in java
Prognoz Technologies Pvt. Ltd.
 
Data Structure and Algorithms Linked List
Data Structure and Algorithms Linked ListData Structure and Algorithms Linked List
Data Structure and Algorithms Linked List
ManishPrajapati78
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Method overriding
Method overridingMethod overriding
Method overriding
Azaz Maverick
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
Haldia Institute of Technology
 
Java Strings
Java StringsJava Strings
Java Strings
RaBiya Chaudhry
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
Hitesh Kumar
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
myrajendra
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
vishal choudhary
 
JTABBED PANE is a swing concept used to have tabs
JTABBED PANE is a swing concept used to have tabsJTABBED PANE is a swing concept used to have tabs
JTABBED PANE is a swing concept used to have tabs
riazahamed37
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
Mohammed Sikander
 
Member Function in C++
Member Function in C++ Member Function in C++
Member Function in C++
NikitaKaur10
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
Ashok Raj
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
Shiv Mehmi
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
Event handling
Event handlingEvent handling
Event handling
swapnac12
 
Data Structure and Algorithms Linked List
Data Structure and Algorithms Linked ListData Structure and Algorithms Linked List
Data Structure and Algorithms Linked List
ManishPrajapati78
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
Hitesh Kumar
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
myrajendra
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
vishal choudhary
 
JTABBED PANE is a swing concept used to have tabs
JTABBED PANE is a swing concept used to have tabsJTABBED PANE is a swing concept used to have tabs
JTABBED PANE is a swing concept used to have tabs
riazahamed37
 
Member Function in C++
Member Function in C++ Member Function in C++
Member Function in C++
NikitaKaur10
 

Similar to Multithreading programming in java (20)

8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Object-Oriented-Prog_MultiThreading.pptx
Object-Oriented-Prog_MultiThreading.pptxObject-Oriented-Prog_MultiThreading.pptx
Object-Oriented-Prog_MultiThreading.pptx
NasreenTaj20
 
multithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptxmultithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
HarshaDokula
 
java programming concept multithreading multitasking.pdf
java programming concept multithreading multitasking.pdfjava programming concept multithreading multitasking.pdf
java programming concept multithreading multitasking.pdf
doraeshin04
 
Module - 5 merged.docx notes about engineering subjects java
Module - 5 merged.docx notes about engineering subjects javaModule - 5 merged.docx notes about engineering subjects java
Module - 5 merged.docx notes about engineering subjects java
KaviShetty
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.ppt
sarthakgithub
 
multithreading to be used in java with good programs.pptx
multithreading to be used in java with good programs.pptxmultithreading to be used in java with good programs.pptx
multithreading to be used in java with good programs.pptx
PriyadharshiniG41
 
Internet Programming with Java
Internet Programming with JavaInternet Programming with Java
Internet Programming with Java
kavitha muneeshwaran
 
Java
JavaJava
Java
kavitha muneeshwaran
 
unit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptxunit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
unit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptxunit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
Module 4 - Part 4 - Multithreaded Programming.pptx
Module 4 - Part 4 - Multithreaded Programming.pptxModule 4 - Part 4 - Multithreaded Programming.pptx
Module 4 - Part 4 - Multithreaded Programming.pptx
FahmaFamzin
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
arnavytstudio2814
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
TabassumMaktum
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
Himanshu Rajput
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
Shipra Swati
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Object-Oriented-Prog_MultiThreading.pptx
Object-Oriented-Prog_MultiThreading.pptxObject-Oriented-Prog_MultiThreading.pptx
Object-Oriented-Prog_MultiThreading.pptx
NasreenTaj20
 
multithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptxmultithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
java programming concept multithreading multitasking.pdf
java programming concept multithreading multitasking.pdfjava programming concept multithreading multitasking.pdf
java programming concept multithreading multitasking.pdf
doraeshin04
 
Module - 5 merged.docx notes about engineering subjects java
Module - 5 merged.docx notes about engineering subjects javaModule - 5 merged.docx notes about engineering subjects java
Module - 5 merged.docx notes about engineering subjects java
KaviShetty
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.ppt
sarthakgithub
 
multithreading to be used in java with good programs.pptx
multithreading to be used in java with good programs.pptxmultithreading to be used in java with good programs.pptx
multithreading to be used in java with good programs.pptx
PriyadharshiniG41
 
unit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptxunit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
unit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptxunit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
Module 4 - Part 4 - Multithreaded Programming.pptx
Module 4 - Part 4 - Multithreaded Programming.pptxModule 4 - Part 4 - Multithreaded Programming.pptx
Module 4 - Part 4 - Multithreaded Programming.pptx
FahmaFamzin
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
arnavytstudio2814
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
TabassumMaktum
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Ad

More from Elizabeth alexander (11)

Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
Elizabeth alexander
 
Java applet
Java appletJava applet
Java applet
Elizabeth alexander
 
Io streams
Io streamsIo streams
Io streams
Elizabeth alexander
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Java interfaces
Java   interfacesJava   interfaces
Java interfaces
Elizabeth alexander
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
Elizabeth alexander
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
Elizabeth alexander
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
Elizabeth alexander
 
Quantitative Aptitude- Number System
Quantitative Aptitude- Number SystemQuantitative Aptitude- Number System
Quantitative Aptitude- Number System
Elizabeth alexander
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Elizabeth alexander
 
Ad

Recently uploaded (20)

Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 

Multithreading programming in java

  • 1. Multithreading Programming in Java Elizabeth Alexander Hindustan University
  • 2. Multithreading ● Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. ● Each part of such program is called a thread. ● Thread is basically a lightweight sub-process within a process ie, a smallest unit of processing. ● Multithreading is are used to achieve multitasking. ● In multithreading ,threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. ● Java Multithreading is mostly used in games, animation etc.
  • 3. Multithreading Cont... ● Multithreading is best in all cases in contrast with single-thread model. ● Single-thread system uses an approach of event loop with polling. ● A single thread in the system runs in an infinite loop. ● Polling the mechanism, that selects a single event from the event queue to choose what to do next. As the event is selected, then event loop forwards the control to the corresponding required event handler. Nothing else can be happened, until the event handler returns. ● Because of this CPU time is wasted. ● Here, only one part of the complete program is dominating the whole system, and preventing the system to execute or start any other process. ● In single-thread model one thread blocks all other threads until its execution completes.
  • 4. Multithreading Cont... ● On other waiting or idle thread can start and acquire the resource which is not in use by the current thread. This causes the wastage of resources. ● Java's multithreading provides benefit in this area by eliminating the loop and polling mechanism, one thread can be paused without stopping the other parts of the program. If any thread is paused or blocked, still other threads continue to run. Advantages of Java Multithreading 1) It doesn't block the user because threads are independent and you can perform multiple operations at same time. 2) You can perform many operations together so it saves time. 3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
  • 5. Thread in java ● A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution. ● Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area.
  • 6. The Java Thread Model(Thread Life Cycle)
  • 7. The Java Thread Model Cont... New/Ready to run ● A new thread begins its life cycle in the new state. ● First time as soon as it gets CPU time. ● It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable ● Under execution. ● After a newly born thread is started, the thread becomes runnable. ● A thread in this state is considered to be executing its task.
  • 8. The Java Thread Model Cont... Waiting/Suspended ● Temporarily not active or under execution. ● Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. ● A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Timed Waiting ● A runnable thread can enter the timed waiting state for a specified interval of time. ● A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
  • 9. The Java Thread Model Cont... Blocked ● Waiting for resources. Resumed ● Suspended thread resumed, and start from where it left off. Terminated (Dead) ● Halts the execution immediately and never resumes. ● A runnable thread enters the terminated state when it completes its task or otherwise terminates.
  • 10. The Java Thread Model Cont...
  • 11. Main thread in Java ● When a Java program starts up, one thread begins running immediately. This is usually called the main thread of our program, because it is the one that is executed when our program begins. Properties : ● It is the parent of all the threads of the program and all other "child" threads will be spawned from it. ● It must be the last thread to finish execution because it performs various shutdown actions How to control Main thread ● The main thread is created automatically when our program is started. ● To control it we must obtain a reference to the main thread. ● This can be done by calling a static method currentThread( ) which is present in Thread class.
  • 12. Main thread in Java ● Its general form is static Thread currentThread( ) ● This method returns a reference to the thread on which it is called. ● The default priority of Main thread is 5 and for all remaining user threads priority will be inherited from parent to child.
  • 13. Flow Diagram of Main Thread
  • 14. Creating a thread ● Java defines two ways by which a thread can be created. ○ By implementing the Runnable interface. ○ By extending the Thread class. Thread class: ● Thread class provide constructors and methods to create and perform operations on a thread. ● Thread class extends Object class and implements Runnable interface. ● The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java. Commonly used Constructors of Thread class: ● Thread() ● Thread(String name) ● Thread(Runnable r) ● Thread(Runnable r,String name)
  • 15. Create a Thread by Extending a Thread Class ● The first way to create a thread is to create a new class that extends Thread class. ● This approach provides more flexibility in handling multiple threads created using available methods in Thread class. Step 1 ● You will need to override run( ) method available in Thread class. ● You must specify the code that your thread will execute inside run() method. ● Syntax of run() method − public void run( ) Step 2 ● Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. ● Syntax of start() method − void start( );
  • 16. Create a Thread by Implementing a Runnable Interface ● The easiest way to create a thread is to create a class that implements the runnable interface ● If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. Step 1 ● You need to implement a run() method provided by a Runnable interface. ● This method provides an entry point for the thread a ● You must specify the code that your thread will execute inside run() method. ● Syntax of the run() method − public void run( ) ● run() method can call other methods, can use other classes and declare variables just like any other normal method. Step 2 ● As a second step, you will instantiate a Thread object using the following constructor − Thread(Runnable threadObj, String threadName);
  • 17. ● Where, threadObj is an instance of a class that implements the Runnableinterface and threadName is the name given to the new thread. Step 3 ● Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. ● Syntax of start() method − void start();
  • 18. Thread Priorities ● In a Multi threading environment, thread scheduler assigns processor to a thread based on priority of thread. ● Whenever we create a thread in Java, it always has some priority assigned to it. ● Priority can either be given by JVM while creating the thread or it can be given by programmer explicitly. ● Accepted value of priority for a thread is in range of 1 to 10. ● There are 3 static variables defined in Thread class for priority. ○ public static int MIN_PRIORITY: This is minimum priority that a thread can have. Value for this is 1. ○ public static int NORM_PRIORITY: This is default priority of a thread if do not explicitly define it. Value for this is 5. ○ public static int MAX_PRIORITY: This is maximum priority of a thread. Value for this is 10.
  • 19. Thread Priorities Cont... Get and Set Thread Priority: ● public final int getPriority(): java.lang.Thread.getPriority() method returns priority of given thread. ● public final void setPriority(int newPriority): java.lang.Thread.setPriority() method changes the priority of thread to the value newPriority. ○ This method throws IllegalArgumentException if value of parameter newPriority goes beyond minimum(1) and maximum(10) limit. Note: ● Thread with highest priority will get execution chance prior to other threads. Suppose there are 3 threads t1, t2 and t3 with priorities 4, 6 and 1. So, thread t2 will execute first based on maximum priority 6 after that t1 will execute and then t3. ● Default priority for main thread is always 5, it can be changed later. Default priority for all other threads depends on the priority of parent thread.
  • 20. Synchronization in Java ● Multi-threaded programs may often come to a situation where multiple threads try to access the same resources and finally produce erroneous results. ● For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file. ● So it needs to be made sure by some synchronization method that only one thread can access the resource at a given point of time.This is implemented using a concept called monitors. ● Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.
  • 21. Synchronization in Java Cont... ● Java programming language provides a way of creating threads and synchronizing their task by using synchronized blocks. We keep shared resources within this block. ● Synchronized blocks in Java are marked with the synchronized keyword. ● All synchronized blocks synchronized on the same object can only have one thread executing inside them at a time. ● All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block. ● General form of a synchronized block: synchronized(sync_object) { // Access shared variables and other // shared resources }
  • 22. Synchronization in Java Cont... ● Here, the sync_object is a reference to an object whose lock associates with the monitor that the synchronized statement represents. ● Synchronization in java is the capability to control the access of multiple threads to any shared resource. ● Java Synchronization is better option where we want to allow only one thread to access the shared resource. Why use Synchronization ● The synchronization is mainly used to ■ To prevent thread interference.:Interference occurs when two operations , running in different threads , but acting on the same data ■ To prevent consistency problem. : Consistency Errors occurs when different threads have inconsistent views of the shared data.
  • 23. Inter-thread communication in Java ● Inter-thread communication or Co-operation is about allowing synchronized threads to communicate with each other. ● In concurrent programming, concurrent accesses to shared resources can lead to unexpected or erroneous behavior, so parts of the program where the shared resource is accessed are protected. This protected section is the critical section or critical region ● Inter-thread communication is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. ● Java uses Inter-thread communication or Co-operation to avoid polling. ○ The process of testing a condition repeatedly till it becomes true is known as polling.
  • 24. Inter-thread communication in Java Cont... ● Polling is usually implemented with the help of loops to check whether a particular condition is true or not. If it is true, certain action is taken. This waste many CPU cycles and makes the implementation inefficient. ● Inter-thread communication is implemented by following methods of Object class: ■ wait() ■ notify() ■ notifyAll()
  • 25. wait() method ● Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
  • 26. notify() method ● Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary. ■ Syntax: public final void notify() notifyAll() method ● Wakes up all threads that are waiting on this object's monitor. ■ Syntax: public final void notifyAll()
  • 28. Concept of Lock in Java ● Synchronization is built around an internal entity known as the lock or monitor. ● Every object has a lock associated with it. ● By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them. Deadlock in java ● Deadlock in java is a part of multithreading. Deadlock can occur in a situation 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.