SlideShare a Scribd company logo
2
Most read
7
Most read
12
Most read
JAVA PROGRAMMING
MULTITHREADING
MULTITHREADING
Java is a multi-threaded programming language which means we can develop multi-
threaded program using Java.
A multi-threaded program contains two or more parts that can run concurrently and
each part can handle a different task at the same time making optimal use of the
available resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing
resources such as a CPU.
 Multi-threading extends the idea of multitasking into applications where you can
subdivide specific operations within a single application into individual threads.
Each of the threads can run in parallel.
The OS divides processing time not only among different applications, but also
among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
Life Cycle of a Thread
A thread goes through various stages in its life cycle.
For example, a thread is born, started, runs, and then dies.
The following diagram shows the complete life cycle of a thread.
The stages of the life cycle :
 New − A new thread begins its life cycle in the new state. It remains in this state
until the program starts the thread. It is also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
 Waiting − 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.
 Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine
the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant
of 1) and MAX_PRIORITY (a constant of 10).
By default, every thread is given priority NORM_PRIORITY (a constant of
5).
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads.
 However, thread priorities cannot guarantee the order in which threads
execute and are very much platform dependent.
Create a Thread by Implementing a Runnable Interface
The class is intended to be executed as a thread then you
can achieve this by implementing a Runnable interface.
Three basic steps −
Step 1
As a first step, to implement a run() method provided bya 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( )
Step 2
 As a second step, instantiate a Thread object using the following
constructor.
Thread(Runnable threadObj, String threadName);
 Where, threadObj is an instance of a class that implements
the Runnable interface
 threadName is the name given to the new thread.
Step 3
Once a Thread object is created, start it by calling start() method, which
executes a call to run( ) method.
Following is a simple syntax of start() method −
void start();
EXAMPLE:
class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Output:
thread is running...
public class Main implements Runnable
{
public static void main(String args[])
{
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the
thread");
}
public void run()
{
System.out.println("This code is running in a
thread");
}
}
Sr.No
.
Method & Description
1 public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2 public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that
Runnable object.
3 public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4 public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5 public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6 public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second
thread terminates or the specified number of milliseconds passes.
7 public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8 public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to
completion.
THREAD 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.
• So there is a need to synchronize the action of multiple threads and make sure that
only one thread can access the resource at a given point in 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.
• 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. Following is the general form of the synchronized statement −
yntax
ynchronized(objectidentifier)
{
Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates
with the monitor that the synchronized statement represents.
Now we are going to see two examples, where we will print a counter
using two different threads. When threads are not synchronized,
hey print counter value which is not in sequence, but when we
print counter by putting inside synchronized() block,
hen it prints counter very much in sequence for both the threads.

More Related Content

What's hot (20)

PPT
Chapter 12 - File Input and Output
Eduardo Bergavera
 
PPS
Files & IO in Java
CIB Egypt
 
PPTX
L21 io streams
teach4uin
 
PPT
Input output streams
Parthipan Parthi
 
PPT
Java stream
Arati Gadgil
 
PPT
14 file handling
APU
 
PPT
Byte stream classes.49
myrajendra
 
PPT
Java IO Package and Streams
babak danyal
 
PDF
Java - File Input Output Concepts
Victer Paul
 
PPT
Java Streams
M Vishnuvardhan Reddy
 
PPT
File Input & Output
PRN USM
 
PPT
Character stream classes introd .51
myrajendra
 
PPTX
Java Input Output (java.io.*)
Om Ganesh
 
PPT
Java Input Output and File Handling
Sunil OS
 
PPTX
Java
Dhruv Sabalpara
 
PPT
Taking User Input in Java
Eftakhairul Islam
 
PDF
32.java input-output
santosh mishra
 
PDF
I/O in java Part 1
ashishspace
 
PPT
Various io stream classes .47
myrajendra
 
PDF
java.io - streams and files
Marcello Thiry
 
Chapter 12 - File Input and Output
Eduardo Bergavera
 
Files & IO in Java
CIB Egypt
 
L21 io streams
teach4uin
 
Input output streams
Parthipan Parthi
 
Java stream
Arati Gadgil
 
14 file handling
APU
 
Byte stream classes.49
myrajendra
 
Java IO Package and Streams
babak danyal
 
Java - File Input Output Concepts
Victer Paul
 
Java Streams
M Vishnuvardhan Reddy
 
File Input & Output
PRN USM
 
Character stream classes introd .51
myrajendra
 
Java Input Output (java.io.*)
Om Ganesh
 
Java Input Output and File Handling
Sunil OS
 
Taking User Input in Java
Eftakhairul Islam
 
32.java input-output
santosh mishra
 
I/O in java Part 1
ashishspace
 
Various io stream classes .47
myrajendra
 
java.io - streams and files
Marcello Thiry
 

Similar to Multithreading in java (20)

PDF
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
PPT
Md09 multithreading
Rakesh Madugula
 
PPTX
Multi threading
gndu
 
PPTX
Multithreading in java
Arafat Hossan
 
PPTX
Multithreading
Ravi Chythanya
 
PPT
multithreading
Rajkattamuri
 
PPT
Java
Khasim Cise
 
PPT
Multithreading
F K
 
PPT
Java Multithreading
Rajkattamuri
 
PPT
Java multithreading
Mohammed625
 
DOCX
Threadnotes
Himanshu Rajput
 
PPTX
Multithreading
sagsharma
 
PPTX
Multithreading in java
JanmejayaPadhiary2
 
PPT
Java
mdfkhan625
 
PDF
Java thread life cycle
Archana Gopinath
 
PPTX
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
PPTX
Thread priorities in java
Ducat India
 
PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
KusumitaSahoo1
 
PPTX
Lecture 23-24.pptx
talha ijaz
 
PPT
Chap2 2 1
Hemo Chella
 
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Md09 multithreading
Rakesh Madugula
 
Multi threading
gndu
 
Multithreading in java
Arafat Hossan
 
Multithreading
Ravi Chythanya
 
multithreading
Rajkattamuri
 
Multithreading
F K
 
Java Multithreading
Rajkattamuri
 
Java multithreading
Mohammed625
 
Threadnotes
Himanshu Rajput
 
Multithreading
sagsharma
 
Multithreading in java
JanmejayaPadhiary2
 
Java thread life cycle
Archana Gopinath
 
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
Thread priorities in java
Ducat India
 
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
KusumitaSahoo1
 
Lecture 23-24.pptx
talha ijaz
 
Chap2 2 1
Hemo Chella
 
Ad

More from Kavitha713564 (14)

PPTX
Python Virtual Machine concept- N.Kavitha.pptx
Kavitha713564
 
PPTX
Operators Concept in Python-N.Kavitha.pptx
Kavitha713564
 
PPTX
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
Kavitha713564
 
PPTX
The Java Server Page in Java Concept.pptx
Kavitha713564
 
PPTX
Programming in python in detail concept .pptx
Kavitha713564
 
PPTX
The Input Statement in Core Python .pptx
Kavitha713564
 
PPTX
The Datatypes Concept in Core Python.pptx
Kavitha713564
 
PPTX
Packages in java
Kavitha713564
 
PPTX
Interface in java
Kavitha713564
 
PPTX
Exception handling in java
Kavitha713564
 
PPTX
Multithreading in java
Kavitha713564
 
DOCX
Methods in Java
Kavitha713564
 
PPTX
Applet in java new
Kavitha713564
 
PPTX
Arrays,string and vector
Kavitha713564
 
Python Virtual Machine concept- N.Kavitha.pptx
Kavitha713564
 
Operators Concept in Python-N.Kavitha.pptx
Kavitha713564
 
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
Kavitha713564
 
The Java Server Page in Java Concept.pptx
Kavitha713564
 
Programming in python in detail concept .pptx
Kavitha713564
 
The Input Statement in Core Python .pptx
Kavitha713564
 
The Datatypes Concept in Core Python.pptx
Kavitha713564
 
Packages in java
Kavitha713564
 
Interface in java
Kavitha713564
 
Exception handling in java
Kavitha713564
 
Multithreading in java
Kavitha713564
 
Methods in Java
Kavitha713564
 
Applet in java new
Kavitha713564
 
Arrays,string and vector
Kavitha713564
 
Ad

Recently uploaded (20)

PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Dimensions of Societal Planning in Commonism
StefanMz
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 

Multithreading in java

  • 2. MULTITHREADING Java is a multi-threaded programming language which means we can develop multi- threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs. By definition, multitasking is when multiple processes share common processing resources such as a CPU.  Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program.
  • 3. Life Cycle of a Thread A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread.
  • 4. The stages of the life cycle :  New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.  Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.  Waiting − 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.  Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates.
  • 5. Thread Priorities: Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads.  However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.
  • 6. Create a Thread by Implementing a Runnable Interface The class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. Three basic steps − Step 1 As a first step, to implement a run() method provided bya 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( )
  • 7. Step 2  As a second step, instantiate a Thread object using the following constructor. Thread(Runnable threadObj, String threadName);  Where, threadObj is an instance of a class that implements the Runnable interface  threadName is the name given to the new thread. Step 3 Once a Thread object is created, start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − void start();
  • 8. EXAMPLE: class Multi extends Thread { public void run() { System.out.println("thread is running..."); } public static void main(String args[]) { Multi t1=new Multi(); t1.start(); } } Output: thread is running...
  • 9. public class Main implements Runnable { public static void main(String args[]) { Main obj = new Main(); Thread thread = new Thread(obj); thread.start(); System.out.println("This code is outside of the thread"); } public void run() { System.out.println("This code is running in a thread"); } }
  • 10. Sr.No . Method & Description 1 public void start() Starts the thread in a separate path of execution, then invokes the run() method on this Thread object. 2 public void run() If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object. 3 public final void setName(String name) Changes the name of the Thread object. There is also a getName() method for retrieving the name. 4 public final void setPriority(int priority) Sets the priority of this Thread object. The possible values are between 1 and 10. 5 public final void setDaemon(boolean on) A parameter of true denotes this Thread as a daemon thread. 6 public final void join(long millisec) The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. 7 public void interrupt() Interrupts this thread, causing it to continue execution if it was blocked for any reason. 8 public final boolean isAlive() Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.
  • 11. THREAD 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. • So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in 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. • 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. Following is the general form of the synchronized statement −
  • 12. yntax ynchronized(objectidentifier) { Access shared variables and other shared resources } Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents. Now we are going to see two examples, where we will print a counter using two different threads. When threads are not synchronized, hey print counter value which is not in sequence, but when we print counter by putting inside synchronized() block, hen it prints counter very much in sequence for both the threads.