SlideShare a Scribd company logo
Multithreading
PRESENTED BY –:
Kartik dube (008)
What is a Process?
 Process is a isolated, independently executing programs
to which OS allocate resources such as memory, file
handlers, security credentials, etc.
 Processes communicate with one another through
mechanisms like sockets, signal handlers, shared
memory, semaphores and files.
What is Thread?
 Threads are called lightweight processes.
 Threads are parts of Processes. So all the threads
created by one particular process can share the
process's resources (memory, file handlers, etc).
 There may be several threads in one process
 Threads are independent because they all have
separate path of execution that’s the reason if an
exception occurs in one thread, it doesn’t affect the
execution of other threads.
Process vs threads
What is Multithreading ?
 The process of executing multiple threads simultaneously is
known as multithreading.
Before we talk about multithreading,
Back in the old days a computer had a single CPU, and was only
capable of executing a single program at a time.
Later came multitasking which meant that computers could
execute multiple programs (processes) at the same time. . The
single CPU was shared between the programs. The operating
system would switch between the programs running, executing
each of them for a little while before switching.
Later yet came multithreading which mean that you could have
multiple threads of execution inside the same program.
Multithreading can be a great way to increase the performance of
some types of programs.
Multithreading extends the idea of multitasking into applications,
so you can subdivide specific operations within a single application
into individual
Threads. Each of the threads can run in parallel.
For example, one subprogram can display an animation on the
screen while another may build the next animation to be
displayed.
Since all the threads are running on a single processor, the flow of
execution is shared between the threads. The java interpreter
handles the switching of control between the threads in such a way
that it appears they are running concurrently.
A Thread is a basic unit of CPU utilization, consisting of a
program counter, a stack, and a set of registers, ( and a thread ID. )
Traditional ( heavyweight ) processes have a single thread of
control - There is one program counter, and one sequence of
instructions that can be carried out at any given time.
As shown in Figure , multi-threaded applications have multiple
threads within a single process, each having their own program
counter, stack and set of registers, but sharing common code, data,
and certain structures such as open files.
Figure - Single-threaded and multithreaded processes
Life Cycle of Thread
 During the life time of a thread, there are many states it
can enter. They include:
1. Newborn state
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
Life Cycle of Thread
1. Newborn State
Thread t1 = new Thread();
In new born state, the thread object is just created but not started yet, we can
say it is inactive. In the above statement t1 thread is created but not started. To
make the thread active, call start() method on the thread object as t1.start(). This
makes the thread active and now eligible to run, now it goes to runnable state.
2. Runnable state (start())
The runnable state means that the thread is ready for execution and is waiting
for the availability of the processor.
2. Runnable state (start())
 When the thread is active, the first and foremost job, it does is calling run()
method.
 When the thread is executing the run() method, we say, the thread is in
runnable state.As it is a callback method, all the code expected to run by the
thread, is written here. In this state, the thread is active.
3. Running State
 Running means that the processor has given its time to the
thread for its execution.
 A running thread may relinquish its control in one of the
following situations:
1. Suspend() and resume() Methods:-
This approach is useful when we want to suspend a
thread for some time due to certain reason, but do
not want to kill it.
Running Runnable Suspended
suspended
resume
2. Sleep() Method :-
This means that the thread is out of the queue during
this time period. The thread re-enter the runnable state
as soon as this time period is elapsed.
Running Runnable Sleeping
sleep(t)
3. Wait() and notify() methods :- blocked until
certain condition occurs
Running Runnable Waiting
wait
notify
4. Blocked State
 A thread is said to be blocked when it is prevented form entering into the
runnable state and subsequently the running state.
 This happens when the thread is suspended, sleeping, or waiting in order to
satisfy certain requirements.
5. Dead State
 A running thread ends its life when is has completed executing its run()
method. It is a natural death.
 However, we can kill it by sending the stop message to it at any state thus
causing a premature death to it.
 A thread can be killed as soon it is born, or while it is running, or even when
it is in “not runnable” (blocked) condition.
State diagram of a thread
yield
Newborn
start
stop
stop
stop
suspended
sleep
wait
resume
notify
Blocked
Dead
Running RunnableActive
Thread
New
Thread
Idle Thread
(Not Runnable)
Killed
Thread
How to create thread
 Thread class provide constructors and methods to
create and perform operations on a thread. Thread
class extends Object class and implements Runnable
interface.
 A new thread can be created in two ways:
 By extending a thread class
 By implementing an interface
Commonly used methods of Thread class:
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread.JVM calls the
run() method on the thread.
• public void sleep(long miliseconds): Causes the currently executing
thread to sleep (temporarily cease execution) for the specified number
of milliseconds.
• public void join(): waits for a thread to die.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the
thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the thread.
• public int getId(): returns the id of the thread.
• public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
• public void suspend(): is used to suspend the thread.
• public void resume(): is used to resume the suspended thread.
• public void stop(): is used to stop the thread..
Create a Thread by Implementing a
Runnable Interface
Step 1 :
As a first step, you need to implement a run() method provided by a Runnable
interface. This method provides an entry point for the thread and you will put
your complete business logic inside this method.
Following is a simple syntax of the run() method −
public void run( )
{
//
}
Thread(Runnable threadObj);
Where, threadObj is an instance of a class that implements the Runnable
interface
Step 2 :
As a second step, you will instantiate a Thread object using the following
constructor −
Create a Thread by Implementing a
Runnable Interface
Step 3 :
Once a Thread object is created, you can start it by calling start() method, which
executes a call to run( ) method. Following is a simple syntax of start() method −
void start();
Create a Thread by Implementing a
Runnable Interface
class TDemo implements Runnable
{
public void run()
{
for(int i=0;i<=5;i++)
{
System.out.println("CONCURRENT THREAD RUNNING
SIMUNTANIOUSLY......!!!.....:"+i);
}
}
}
class Main_TDemo1
{
public static void main(String arg[])
{
TDemo obj = new TDemo();
Thread t = new Thread(obj);
t.start();
}
}
Example
Output :
Create a Thread by
Extending the Thread class
 We can directly extend the Thread class
 The class TDemo extends Thread. The logic for the
thread is contained in the run() method.
class TDemo extends Thread
{
public void run()
{
for(int i=0;i<=5;i++)
{
System.out.println("CONCURRENT THREAD RUNNING
SIMUNTANIOUSLY......!!!.....:"+i);
}
}
}
class Main_TDemo1
{
public static void main(String arg[])
{
TDemo obj = new TDemo();
obj.start();
}
}
Example
Output :
Synchronization
 When we start two or more threads within a program,
there may be a situation when multiple threads try to
access the same resource and finally they can produce
unforeseen result due to concurrency issues.
 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.
 Java programming language provides a very handy way of
creating threads and synchronizing their task by
using synchronized blocks. You keep shared resources within this
block
synchronized (object)
{
//statement to be synchronized
}
Synchronization
Why use Synchronization
The synchronization is mainly used to :-
• To prevent thread interference.
• To prevent consistency problem.
class MDemo
{
public static void main(String arg[])throws InterruptedException
{
SDemo obj = new SDemo();
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
t1.start();
t2.start();
}
}
class SDemo implements Runnable
{
int avail = 1;
int req = 1;
public void run()
{
System.out.println("AVAILABLE BIRTH = "+avail);
synchronized(this)
{
if(avail >= req)
{
System.out.println("1 BIRTH IS RESERVED");
try
{
Thread.sleep(2000);
avail = avail-req;
}
catch(Exception e){}
}
else
System.out.println("RECENTLY NO BIRTH AVAILABLE ");
}
}
}
Thank You..!!

More Related Content

PPTX
MULTI THREADING IN JAVA
VINOTH R
 
PPT
Basic of Multithreading in JAva
suraj pandey
 
PPTX
Multithread Programing in Java
M. Raihan
 
PPT
12 multi-threading
APU
 
PDF
Java Thread Synchronization
Benj Del Mundo
 
ODP
Multithreading Concepts
Arvind Krishnaa
 
PPT
Synchronization.37
myrajendra
 
PPSX
Multithreading in-java
aalipalh
 
MULTI THREADING IN JAVA
VINOTH R
 
Basic of Multithreading in JAva
suraj pandey
 
Multithread Programing in Java
M. Raihan
 
12 multi-threading
APU
 
Java Thread Synchronization
Benj Del Mundo
 
Multithreading Concepts
Arvind Krishnaa
 
Synchronization.37
myrajendra
 
Multithreading in-java
aalipalh
 

What's hot (19)

ODP
Multithreading In Java
parag
 
PPT
Thread
Juhi Kumari
 
PDF
Java threading
Chinh Ngo Nguyen
 
PPTX
L22 multi-threading-introduction
teach4uin
 
PPT
Learning Java 3 – Threads and Synchronization
caswenson
 
PPT
Java Multithreading
Rajkattamuri
 
PPTX
Multi threading
Mavoori Soshmitha
 
PPT
Thread model in java
AmbigaMurugesan
 
PPT
Developing Multithreaded Applications
Bharat17485
 
PPTX
Java Thread & Multithreading
jehan1987
 
PPTX
Multithreading in java
Arafat Hossan
 
PPT
Java Threads and Concurrency
Sunil OS
 
PDF
Multithreading in Java
Appsterdam Milan
 
PPT
Threads in Java
Gaurav Aggarwal
 
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
choksheak
 
PPT
Java multi threading
Raja Sekhar
 
PPT
Java And Multithreading
Shraddha
 
PDF
javathreads
Arjun Shanka
 
PPTX
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Multithreading In Java
parag
 
Thread
Juhi Kumari
 
Java threading
Chinh Ngo Nguyen
 
L22 multi-threading-introduction
teach4uin
 
Learning Java 3 – Threads and Synchronization
caswenson
 
Java Multithreading
Rajkattamuri
 
Multi threading
Mavoori Soshmitha
 
Thread model in java
AmbigaMurugesan
 
Developing Multithreaded Applications
Bharat17485
 
Java Thread & Multithreading
jehan1987
 
Multithreading in java
Arafat Hossan
 
Java Threads and Concurrency
Sunil OS
 
Multithreading in Java
Appsterdam Milan
 
Threads in Java
Gaurav Aggarwal
 
Advanced Introduction to Java Multi-Threading - Full (chok)
choksheak
 
Java multi threading
Raja Sekhar
 
Java And Multithreading
Shraddha
 
javathreads
Arjun Shanka
 
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Ad

Similar to Multithreading Introduction and Lifecyle of thread (20)

PPTX
Multithreading in java
Monika Mishra
 
DOCX
Threadnotes
Himanshu Rajput
 
PPTX
Multithreading
sagsharma
 
PPTX
MSBTE Computer Engineering JPR java. multi. threading.pptx
kunalgaikwad1705
 
PPTX
Multithreading.pptx
PragatiSutar4
 
PPTX
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
PPTX
econtent thread in java.pptx
ramyan49
 
PPTX
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
PPTX
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
PPTX
Internet Programming with Java
kavitha muneeshwaran
 
PPT
Chap2 2 1
Hemo Chella
 
PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
KusumitaSahoo1
 
PPTX
Object-Oriented-Prog_MultiThreading.pptx
NasreenTaj20
 
PPTX
Multithreading in java
Kavitha713564
 
PPTX
Multithreading in java
Kavitha713564
 
PDF
Java unit 12
Shipra Swati
 
PPTX
Multithreading in java
junnubabu
 
PPTX
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
PDF
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
Multithreading in java
Monika Mishra
 
Threadnotes
Himanshu Rajput
 
Multithreading
sagsharma
 
MSBTE Computer Engineering JPR java. multi. threading.pptx
kunalgaikwad1705
 
Multithreading.pptx
PragatiSutar4
 
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
econtent thread in java.pptx
ramyan49
 
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
Internet Programming with Java
kavitha muneeshwaran
 
Chap2 2 1
Hemo Chella
 
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
KusumitaSahoo1
 
Object-Oriented-Prog_MultiThreading.pptx
NasreenTaj20
 
Multithreading in java
Kavitha713564
 
Multithreading in java
Kavitha713564
 
Java unit 12
Shipra Swati
 
Multithreading in java
junnubabu
 
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
Ad

Recently uploaded (20)

PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PDF
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
mansk2
 
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PDF
Introducing Procurement and Supply L2M1.pdf
labyankof
 
PDF
Module 3: Health Systems Tutorial Slides S2 2025
Jonathan Hallett
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mithil Fal Desai
 
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
TumwineRobert
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PDF
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
Week 4 Term 3 Study Techniques revisited.pptx
mansk2
 
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Introducing Procurement and Supply L2M1.pdf
labyankof
 
Module 3: Health Systems Tutorial Slides S2 2025
Jonathan Hallett
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mithil Fal Desai
 
Cardiovascular Pharmacology for pharmacy students.pptx
TumwineRobert
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 

Multithreading Introduction and Lifecyle of thread

  • 2. What is a Process?
  • 3.  Process is a isolated, independently executing programs to which OS allocate resources such as memory, file handlers, security credentials, etc.  Processes communicate with one another through mechanisms like sockets, signal handlers, shared memory, semaphores and files.
  • 5.  Threads are called lightweight processes.  Threads are parts of Processes. So all the threads created by one particular process can share the process's resources (memory, file handlers, etc).  There may be several threads in one process  Threads are independent because they all have separate path of execution that’s the reason if an exception occurs in one thread, it doesn’t affect the execution of other threads.
  • 7. What is Multithreading ?  The process of executing multiple threads simultaneously is known as multithreading.
  • 8. Before we talk about multithreading, Back in the old days a computer had a single CPU, and was only capable of executing a single program at a time. Later came multitasking which meant that computers could execute multiple programs (processes) at the same time. . The single CPU was shared between the programs. The operating system would switch between the programs running, executing each of them for a little while before switching. Later yet came multithreading which mean that you could have multiple threads of execution inside the same program.
  • 9. Multithreading can be a great way to increase the performance of some types of programs. Multithreading extends the idea of multitasking into applications, so you can subdivide specific operations within a single application into individual Threads. Each of the threads can run in parallel. For example, one subprogram can display an animation on the screen while another may build the next animation to be displayed. Since all the threads are running on a single processor, the flow of execution is shared between the threads. The java interpreter handles the switching of control between the threads in such a way that it appears they are running concurrently.
  • 10. A Thread is a basic unit of CPU utilization, consisting of a program counter, a stack, and a set of registers, ( and a thread ID. ) Traditional ( heavyweight ) processes have a single thread of control - There is one program counter, and one sequence of instructions that can be carried out at any given time. As shown in Figure , multi-threaded applications have multiple threads within a single process, each having their own program counter, stack and set of registers, but sharing common code, data, and certain structures such as open files.
  • 11. Figure - Single-threaded and multithreaded processes
  • 12. Life Cycle of Thread  During the life time of a thread, there are many states it can enter. They include: 1. Newborn state 2. Runnable State 3. Running State 4. Blocked State 5. Dead State
  • 13. Life Cycle of Thread
  • 14. 1. Newborn State Thread t1 = new Thread(); In new born state, the thread object is just created but not started yet, we can say it is inactive. In the above statement t1 thread is created but not started. To make the thread active, call start() method on the thread object as t1.start(). This makes the thread active and now eligible to run, now it goes to runnable state.
  • 15. 2. Runnable state (start()) The runnable state means that the thread is ready for execution and is waiting for the availability of the processor.
  • 16. 2. Runnable state (start())  When the thread is active, the first and foremost job, it does is calling run() method.  When the thread is executing the run() method, we say, the thread is in runnable state.As it is a callback method, all the code expected to run by the thread, is written here. In this state, the thread is active.
  • 17. 3. Running State  Running means that the processor has given its time to the thread for its execution.  A running thread may relinquish its control in one of the following situations:
  • 18. 1. Suspend() and resume() Methods:- This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it. Running Runnable Suspended suspended resume
  • 19. 2. Sleep() Method :- This means that the thread is out of the queue during this time period. The thread re-enter the runnable state as soon as this time period is elapsed. Running Runnable Sleeping sleep(t)
  • 20. 3. Wait() and notify() methods :- blocked until certain condition occurs Running Runnable Waiting wait notify
  • 21. 4. Blocked State  A thread is said to be blocked when it is prevented form entering into the runnable state and subsequently the running state.  This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain requirements.
  • 22. 5. Dead State  A running thread ends its life when is has completed executing its run() method. It is a natural death.  However, we can kill it by sending the stop message to it at any state thus causing a premature death to it.  A thread can be killed as soon it is born, or while it is running, or even when it is in “not runnable” (blocked) condition.
  • 23. State diagram of a thread yield Newborn start stop stop stop suspended sleep wait resume notify Blocked Dead Running RunnableActive Thread New Thread Idle Thread (Not Runnable) Killed Thread
  • 24. How to create thread  Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.  A new thread can be created in two ways:  By extending a thread class  By implementing an interface
  • 25. Commonly used methods of Thread class: • public void run(): is used to perform action for a thread. • public void start(): starts the execution of the thread.JVM calls the run() method on the thread. • public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. • public void join(): waits for a thread to die. • public int getPriority(): returns the priority of the thread. • public int setPriority(int priority): changes the priority of the thread. • public String getName(): returns the name of the thread. • public void setName(String name): changes the name of the thread. • public int getId(): returns the id of the thread. • public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. • public void suspend(): is used to suspend the thread. • public void resume(): is used to resume the suspended thread. • public void stop(): is used to stop the thread..
  • 26. Create a Thread by Implementing a Runnable Interface Step 1 : As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method − public void run( ) { // }
  • 27. Thread(Runnable threadObj); Where, threadObj is an instance of a class that implements the Runnable interface Step 2 : As a second step, you will instantiate a Thread object using the following constructor − Create a Thread by Implementing a Runnable Interface
  • 28. Step 3 : Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start(); Create a Thread by Implementing a Runnable Interface
  • 29. class TDemo implements Runnable { public void run() { for(int i=0;i<=5;i++) { System.out.println("CONCURRENT THREAD RUNNING SIMUNTANIOUSLY......!!!.....:"+i); } } } class Main_TDemo1 { public static void main(String arg[]) { TDemo obj = new TDemo(); Thread t = new Thread(obj); t.start(); } } Example
  • 31. Create a Thread by Extending the Thread class  We can directly extend the Thread class  The class TDemo extends Thread. The logic for the thread is contained in the run() method.
  • 32. class TDemo extends Thread { public void run() { for(int i=0;i<=5;i++) { System.out.println("CONCURRENT THREAD RUNNING SIMUNTANIOUSLY......!!!.....:"+i); } } } class Main_TDemo1 { public static void main(String arg[]) { TDemo obj = new TDemo(); obj.start(); } } Example
  • 34. Synchronization  When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues.  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.
  • 35.  Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block synchronized (object) { //statement to be synchronized } Synchronization
  • 36. Why use Synchronization The synchronization is mainly used to :- • To prevent thread interference. • To prevent consistency problem.
  • 37. class MDemo { public static void main(String arg[])throws InterruptedException { SDemo obj = new SDemo(); Thread t1 = new Thread(obj); Thread t2 = new Thread(obj); t1.start(); t2.start(); } }
  • 38. class SDemo implements Runnable { int avail = 1; int req = 1; public void run() { System.out.println("AVAILABLE BIRTH = "+avail); synchronized(this) { if(avail >= req) { System.out.println("1 BIRTH IS RESERVED"); try { Thread.sleep(2000); avail = avail-req; } catch(Exception e){} } else System.out.println("RECENTLY NO BIRTH AVAILABLE "); } } }