SlideShare a Scribd company logo
1 of 4
THREADS IN JAVA
 What Is a Thread
A “thread” is a single sequential flow of control within a program.
When multiple threads execute byte-code instruction sequences in the same
program, that action is known as “Multithreading”. Multithreading benefits a program in
different ways:
Multithreaded GUI (graphical user interface)-based programs remain responsive to
users while performing other tasks, such as repaginating or printing a document.
Threaded programs typically finish faster than their nonthreaded counterparts. This is
especially true of threads running on a multiprocessor machine, where each thread
has its own processor.
Java accomplishes multithreading through its java.lang.Thread class. Each Thread object
describes a single thread of execution. That execution occurs in Thread's run() method.
Because the default run() method does nothing, you must subclass Thread and override
run() to accomplish useful work. For a taste of threads and multithreading in the context of
Thread.

 Process vs. threads
A process runs independently and isolated of other processes. It cannot directly access
shared data in other processes. The resources of the process.
Ex: memory and CPU time, are allocated to it via the operating system.
A thread is a so called lightweight process. It has its own call stack, but can access shared
data of other threads in the same process. Every thread has its own memory cache. If a
thread reads shared data it stores this data in its own memory cache. A thread can re-read
the shared data.
A Java application runs by default in one process. Within a Java application you work
with several threads to achieve parallel processing or asynchronous behavior.

 create using Thread class
An application that creates an instance of Thread must provide the code that will run in that
thread.

www.p2cinfotech.com

+1-732-546-3607
THREADS IN JAVA
There are two ways to create a new thread
1) Extend the Thread class and override the run() method in your class. Create an
instance of the subclass and invoke the start() method on it, which will create a new thread of
execution.

Example:
public class NewThread extends Thread{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
c.start();
}
}
2) Implements the Runnable interface. The class will have to implement the run()
method in the Runnable interface. Create an instance of this class. Pass the reference of this
instance to the Thread constructor a new thread of execution will be created.

Example:
public class NewThread implements Runnable{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
Thread t = new Thread(c);
t.start();
}
}

Synchronization:
Synchronization is the process of allowing threads to execute one after another.

www.p2cinfotech.com

+1-732-546-3607
THREADS IN JAVA
Synchronization control the access the multiple threads to a shared resources.
Without synchronization of threads, one thread can modify a shared variable while another
thread can update the same shared variable, which leads to significant errors.
To make a method synchronized, simply add the synchronized keyword to its declaration.
The only real difference is that a synchronized block can choose which object it synchronizes
on. A synchronized method can only use 'this' (or the corresponding Class instance for a
synchronized class method).

 Life Cycle of Thread

The different states of threads are as follows:
1) New : When a thread is instantiated it is in New state until the start() method is called on the
thread instance. In this state the thread is not considered to be alive.

www.p2cinfotech.com

+1-732-546-3607
THREADS IN JAVA
2) Runnable : The thread enters into this state after the start method is called in the thread
instance. The thread may enter into the Runnable state from Running state. In this state the
thread is considered to be alive.
3) Running : When the thread scheduler picks up the thread from the Runnable thread’s pool,
the thread starts running and the thread is said to be in Running state.

4) Waiting/Blocked/Sleeping : In these states the thread is said to be alive but not runnable.
The thread switches to this state because of reasons like wait method called or sleep method
has been called on the running thread or thread might be waiting for some i/o resource so
blocked.
5) Dead : When the thread finishes its execution i.e. the run() method execution completes, it is
said to be in dead state. A dead state can not be started again. If a start() method is invoked on
a dead thread a runtime exception will occur.

www.p2cinfotech.com

+1-732-546-3607

More Related Content

Viewers also liked

Viewers also liked (19)

Savr
SavrSavr
Savr
 
02basics
02basics02basics
02basics
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
 
Java quick reference v2
Java quick reference v2Java quick reference v2
Java quick reference v2
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Singleton pattern
Singleton patternSingleton pattern
Singleton pattern
 
Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
 
Java Basic Operators
Java Basic OperatorsJava Basic Operators
Java Basic Operators
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
 
Yaazli International Java Training
Yaazli International Java Training Yaazli International Java Training
Yaazli International Java Training
 
java swing
java swingjava swing
java swing
 
Java notes 1 - operators control-flow
Java notes   1 - operators control-flowJava notes   1 - operators control-flow
Java notes 1 - operators control-flow
 
Loadrunner interview questions and answers
Loadrunner interview questions and answersLoadrunner interview questions and answers
Loadrunner interview questions and answers
 
Short definitions of all testing types
Short definitions of all testing typesShort definitions of all testing types
Short definitions of all testing types
 

More from Garuda Trainings

Software testing life cycle
Software testing life cycleSoftware testing life cycle
Software testing life cycleGaruda Trainings
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in javaGaruda Trainings
 
Performance testing interview questions and answers
Performance testing interview questions and answersPerformance testing interview questions and answers
Performance testing interview questions and answersGaruda Trainings
 
Business analysis interview question and answers
Business analysis interview question and answersBusiness analysis interview question and answers
Business analysis interview question and answersGaruda Trainings
 
Quality center interview questions and answers
Quality center interview questions and answersQuality center interview questions and answers
Quality center interview questions and answersGaruda Trainings
 
Software development life cycle
Software development life cycleSoftware development life cycle
Software development life cycleGaruda Trainings
 
Interview Questions and Answers for Java
Interview Questions and Answers for JavaInterview Questions and Answers for Java
Interview Questions and Answers for JavaGaruda Trainings
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobGaruda Trainings
 
Dot net Online Training | .Net Training and Placement online
Dot net Online Training | .Net Training and Placement onlineDot net Online Training | .Net Training and Placement online
Dot net Online Training | .Net Training and Placement onlineGaruda Trainings
 
Interview questions and answers for quality assurance
Interview questions and answers for quality assuranceInterview questions and answers for quality assurance
Interview questions and answers for quality assuranceGaruda Trainings
 
Unix commands in etl testing
Unix commands in etl testingUnix commands in etl testing
Unix commands in etl testingGaruda Trainings
 

More from Garuda Trainings (13)

SAP BI 7.0 Info Providers
SAP BI 7.0 Info ProvidersSAP BI 7.0 Info Providers
SAP BI 7.0 Info Providers
 
Software testing life cycle
Software testing life cycleSoftware testing life cycle
Software testing life cycle
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
 
Performance testing interview questions and answers
Performance testing interview questions and answersPerformance testing interview questions and answers
Performance testing interview questions and answers
 
Business analysis interview question and answers
Business analysis interview question and answersBusiness analysis interview question and answers
Business analysis interview question and answers
 
Quality center interview questions and answers
Quality center interview questions and answersQuality center interview questions and answers
Quality center interview questions and answers
 
Software development life cycle
Software development life cycleSoftware development life cycle
Software development life cycle
 
Interview Questions and Answers for Java
Interview Questions and Answers for JavaInterview Questions and Answers for Java
Interview Questions and Answers for Java
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
Dot net Online Training | .Net Training and Placement online
Dot net Online Training | .Net Training and Placement onlineDot net Online Training | .Net Training and Placement online
Dot net Online Training | .Net Training and Placement online
 
Interview questions and answers for quality assurance
Interview questions and answers for quality assuranceInterview questions and answers for quality assurance
Interview questions and answers for quality assurance
 
Unix commands in etl testing
Unix commands in etl testingUnix commands in etl testing
Unix commands in etl testing
 
SQL for ETL Testing
SQL for ETL TestingSQL for ETL Testing
SQL for ETL Testing
 

Recently uploaded

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 

Recently uploaded (20)

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 

Threads in java

  • 1. THREADS IN JAVA  What Is a Thread A “thread” is a single sequential flow of control within a program. When multiple threads execute byte-code instruction sequences in the same program, that action is known as “Multithreading”. Multithreading benefits a program in different ways: Multithreaded GUI (graphical user interface)-based programs remain responsive to users while performing other tasks, such as repaginating or printing a document. Threaded programs typically finish faster than their nonthreaded counterparts. This is especially true of threads running on a multiprocessor machine, where each thread has its own processor. Java accomplishes multithreading through its java.lang.Thread class. Each Thread object describes a single thread of execution. That execution occurs in Thread's run() method. Because the default run() method does nothing, you must subclass Thread and override run() to accomplish useful work. For a taste of threads and multithreading in the context of Thread.  Process vs. threads A process runs independently and isolated of other processes. It cannot directly access shared data in other processes. The resources of the process. Ex: memory and CPU time, are allocated to it via the operating system. A thread is a so called lightweight process. It has its own call stack, but can access shared data of other threads in the same process. Every thread has its own memory cache. If a thread reads shared data it stores this data in its own memory cache. A thread can re-read the shared data. A Java application runs by default in one process. Within a Java application you work with several threads to achieve parallel processing or asynchronous behavior.  create using Thread class An application that creates an instance of Thread must provide the code that will run in that thread. www.p2cinfotech.com +1-732-546-3607
  • 2. THREADS IN JAVA There are two ways to create a new thread 1) Extend the Thread class and override the run() method in your class. Create an instance of the subclass and invoke the start() method on it, which will create a new thread of execution. Example: public class NewThread extends Thread{ public void run(){ // the code that has to be executed in a separate new thread goes here } public static void main(String [] args){ NewThread c = new NewThread(); c.start(); } } 2) Implements the Runnable interface. The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new thread of execution will be created. Example: public class NewThread implements Runnable{ public void run(){ // the code that has to be executed in a separate new thread goes here } public static void main(String [] args){ NewThread c = new NewThread(); Thread t = new Thread(c); t.start(); } } Synchronization: Synchronization is the process of allowing threads to execute one after another. www.p2cinfotech.com +1-732-546-3607
  • 3. THREADS IN JAVA Synchronization control the access the multiple threads to a shared resources. Without synchronization of threads, one thread can modify a shared variable while another thread can update the same shared variable, which leads to significant errors. To make a method synchronized, simply add the synchronized keyword to its declaration. The only real difference is that a synchronized block can choose which object it synchronizes on. A synchronized method can only use 'this' (or the corresponding Class instance for a synchronized class method).  Life Cycle of Thread The different states of threads are as follows: 1) New : When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive. www.p2cinfotech.com +1-732-546-3607
  • 4. THREADS IN JAVA 2) Runnable : The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive. 3) Running : When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts running and the thread is said to be in Running state. 4) Waiting/Blocked/Sleeping : In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked. 5) Dead : When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur. www.p2cinfotech.com +1-732-546-3607