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)

PPTX
JAVA AWT
shanmuga rajan
 
PPTX
Java media framework
Payal Vishwakarma
 
PPTX
Threads in JAVA
Haldia Institute of Technology
 
PPTX
Abstract class and Interface
Haris Bin Zahid
 
PPTX
Java awt (abstract window toolkit)
Elizabeth alexander
 
PPTX
Access specifiers(modifiers) in java
HrithikShinde
 
PPTX
JDBC ppt
Rohit Jain
 
PPSX
JDBC: java DataBase connectivity
Tanmoy Barman
 
PPSX
Introduction to java
Ajay Sharma
 
PPTX
Multi-threaded Programming in JAVA
Vikram Kalyani
 
PPTX
AWT Packages , Containers and Components
Sohanur63
 
PPTX
MULTI THREADING IN JAVA
VINOTH R
 
PPTX
This keyword in java
Hitesh Kumar
 
PPT
Abstract class
Tony Nguyen
 
PPT
Java static keyword
Lovely Professional University
 
PPT
C# Exceptions Handling
sharqiyem
 
PPTX
Inner classes in java
PhD Research Scholar
 
PPT
Inheritance and Polymorphism
BG Java EE Course
 
PPTX
Abstract Class & Abstract Method in Core Java
MOHIT AGARWAL
 
PDF
Java collections
Hamid Ghorbani
 
JAVA AWT
shanmuga rajan
 
Java media framework
Payal Vishwakarma
 
Abstract class and Interface
Haris Bin Zahid
 
Java awt (abstract window toolkit)
Elizabeth alexander
 
Access specifiers(modifiers) in java
HrithikShinde
 
JDBC ppt
Rohit Jain
 
JDBC: java DataBase connectivity
Tanmoy Barman
 
Introduction to java
Ajay Sharma
 
Multi-threaded Programming in JAVA
Vikram Kalyani
 
AWT Packages , Containers and Components
Sohanur63
 
MULTI THREADING IN JAVA
VINOTH R
 
This keyword in java
Hitesh Kumar
 
Abstract class
Tony Nguyen
 
Java static keyword
Lovely Professional University
 
C# Exceptions Handling
sharqiyem
 
Inner classes in java
PhD Research Scholar
 
Inheritance and Polymorphism
BG Java EE Course
 
Abstract Class & Abstract Method in Core Java
MOHIT AGARWAL
 
Java collections
Hamid Ghorbani
 

Similar to Multithreading programming in java (20)

PDF
Java Threads: Lightweight Processes
Isuru Perera
 
PPTX
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
PPTX
Threads in Java
HarshaDokula
 
PPTX
Module 4 - Part 4 - Multithreaded Programming.pptx
FahmaFamzin
 
PPTX
U4 JAVA.pptx
madan r
 
PPTX
Multithreading in java
Kavitha713564
 
PPTX
Multithreading in java
Kavitha713564
 
PPT
Md09 multithreading
Rakesh Madugula
 
PPTX
Multithreading in java
JanmejayaPadhiary2
 
PPTX
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
PDF
Java unit 12
Shipra Swati
 
PDF
Linux Internals - Part III
Emertxe Information Technologies Pvt Ltd
 
PDF
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
universitypresidency
 
PPTX
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
PPTX
Java-Threads And Concurrency Presentation. 2024
nehakumari0xf
 
PPTX
Java Threads And Concurrency Presentation. 2024
kashyapneha2809
 
PPTX
Multi-Threading in Java power point presenetation
AshokRachapalli1
 
PPT
Chap2 2 1
Hemo Chella
 
PDF
Unit-3 MULTITHREADING-2.pdf
GouthamSoma1
 
PDF
Java Threads
Hamid Ghorbani
 
Java Threads: Lightweight Processes
Isuru Perera
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
Threads in Java
HarshaDokula
 
Module 4 - Part 4 - Multithreaded Programming.pptx
FahmaFamzin
 
U4 JAVA.pptx
madan r
 
Multithreading in java
Kavitha713564
 
Multithreading in java
Kavitha713564
 
Md09 multithreading
Rakesh Madugula
 
Multithreading in java
JanmejayaPadhiary2
 
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
Java unit 12
Shipra Swati
 
Linux Internals - Part III
Emertxe Information Technologies Pvt Ltd
 
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
universitypresidency
 
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
Java-Threads And Concurrency Presentation. 2024
nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
kashyapneha2809
 
Multi-Threading in Java power point presenetation
AshokRachapalli1
 
Chap2 2 1
Hemo Chella
 
Unit-3 MULTITHREADING-2.pdf
GouthamSoma1
 
Java Threads
Hamid Ghorbani
 
Ad

More from Elizabeth alexander (10)

PPTX
Java applet
Elizabeth alexander
 
PPTX
Io streams
Elizabeth alexander
 
PPTX
Exception handling in java
Elizabeth alexander
 
PPTX
Packages in java
Elizabeth alexander
 
PPTX
Java interfaces
Elizabeth alexander
 
PPTX
Polymorphism in java
Elizabeth alexander
 
PPTX
Inheritance in Java
Elizabeth alexander
 
PPTX
Object oriented programming in java
Elizabeth alexander
 
PPTX
Quantitative Aptitude- Number System
Elizabeth alexander
 
PPTX
Java Programming
Elizabeth alexander
 
Java applet
Elizabeth alexander
 
Exception handling in java
Elizabeth alexander
 
Packages in java
Elizabeth alexander
 
Java interfaces
Elizabeth alexander
 
Polymorphism in java
Elizabeth alexander
 
Inheritance in Java
Elizabeth alexander
 
Object oriented programming in java
Elizabeth alexander
 
Quantitative Aptitude- Number System
Elizabeth alexander
 
Java Programming
Elizabeth alexander
 
Ad

Recently uploaded (20)

PPTX
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
PDF
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
PPTX
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
PPTX
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PPT
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PDF
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PDF
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PPTX
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
MRRS Strength and Durability of Concrete
CivilMythili
 
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
AN EMPIRICAL STUDY ON THE USAGE OF SOCIAL MEDIA IN GERMAN B2C-ONLINE STORES
ijait
 
Design Thinking basics for Engineers.pdf
CMR University
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 

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.