SlideShare a Scribd company logo
THREADS
Mr.V.M.Prabhakaran,
Department of CSE,
KIT- Coimbatore
INTRODUCTION
• A thread is an independent path of execution
within a program.
• Many threads can run concurrently within a
program.
• Every thread in Java is created and controlled
by the java.lang.Thread class.
• A Java program can have many threads, and
these threads can run concurrently, either
asynchronously or synchronously.
• Thread is a lightweight sub
process
• 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.
• Thread is executed inside the
process. There is context-
switching between the threads.
There can be multiple
processes inside the OS and
one process can have multiple
threads.
Multitasking and Multithreading
• Multitasking:
– refers to a computer's ability to perform multiple jobs
concurrently
– more than one program are running concurrently, e.g., UNIX
• Multithreading:
– A thread is a single sequence of execution within a program
– refers to multiple threads of control within a single program
– each program can run multiple threads of control within it,
e.g., Web Browser
4
Concurrency vs. Parallelism
5
CPU CPU1 CPU2
What are Threads Good For?
• To maintain responsiveness of an application during a
long running task
• To enable cancellation of separable tasks
• Some problems are intrinsically parallel
• To monitor status of some resource (e.g., DB)
• Some APIs and systems demand it (e.g., Swing)
6
Advantage 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.
Life cycle of a Thread
The life cycle of the thread
in java is controlled by
JVM. The java thread
states are as follows:
– New
– Runnable
– Running
– Non-Runnable (Blocked)
– Terminated
Life cycle of a Thread (Contd)
• 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.
Daemon thread
• Daemon thread is a low priority thread (in
context of JVM) that runs in background to
perform tasks such as garbage collection.
• JVM terminates itself when all user threads
(non-daemon threads) finish their execution,
JVM does not care whether Daemon thread is
running or not,
Thread Priority
• When a Java thread is created, it inherits its
priority from the thread that created it.
• You can modify a thread’s priority at any time
after its creation using the setPriority method.
• Thread priorities are integers ranging between
• MIN_PRIORITY (1)
• NORM_PRIORITY (5)
• MAX_PRIORITY (10)
Creating Threads
• There are two ways to create our own Thread
object
– By extending Thread class
– By implementing Runnable interface.
• In both cases the run() method should be
implemented
Commonly used Constructors of
Thread class
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
Extending Thread
SYNTAX
class Mythread extends Thread
{
public void run(){
--------------
--------------
--------------
--------------
}
}
PROGRAM
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...
Thread Methods
void start()
– Creates a new thread and makes it runnable
– This method can be called only once
void run()
– The new thread begins its life inside this method
void stop() (deprecated)
– The thread is being terminated
Thread Methods
void yield()
– Causes the currently executing thread object to
temporarily pause and allow other threads to
execute
– Allow only threads of the same priority to run
void sleep(int m) or sleep(int m, int n)
– The thread sleeps for m milliseconds, plus n
nanoseconds
Thread Methods
• public void start()
• public void run()
• public final void
setName(String name)
• public final void
setPriority(int priority)
• public final void
setDaemon(boolean on)
• public final void join(long
millisec)
• public void interrupt()
• public final boolean
isAlive()
• public static void yield()
• public static void sleep(long
millisec)
• public static boolean
holdsLock(Object x)
• public static Thread
currentThread()
• public static void
dumpStack()
Implementing Runnable
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output: thread is running...

More Related Content

What's hot

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 

What's hot (20)

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Applets
AppletsApplets
Applets
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 

Similar to Java threads

Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
ssusere538f7
 

Similar to Java threads (20)

U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Lec 1.10 Object Oriented Programming
Lec 1.10 Object Oriented ProgrammingLec 1.10 Object Oriented Programming
Lec 1.10 Object Oriented Programming
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Java threading
Java threadingJava threading
Java threading
 
Thread
ThreadThread
Thread
 
Thread
ThreadThread
Thread
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.ppt
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Multi threading
Multi threadingMulti threading
Multi threading
 
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part IIPROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part II
 
Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
 
thread os.pptx
thread os.pptxthread os.pptx
thread os.pptx
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 

More from Prabhakaran V M (7)

Strings in python
Strings in pythonStrings in python
Strings in python
 
Operators in python
Operators in pythonOperators in python
Operators in python
 
Algorithmic problem solving
Algorithmic problem solvingAlgorithmic problem solving
Algorithmic problem solving
 
Open mp directives
Open mp directivesOpen mp directives
Open mp directives
 
Xml schema
Xml schemaXml schema
Xml schema
 
Html 5
Html 5Html 5
Html 5
 
Introduction to Multi-core Architectures
Introduction to Multi-core ArchitecturesIntroduction to Multi-core Architectures
Introduction to Multi-core Architectures
 

Recently uploaded

JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
Max Lee
 

Recently uploaded (20)

Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
iGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockiGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by Skilrock
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
Benefits of Employee Monitoring Software
Benefits of  Employee Monitoring SoftwareBenefits of  Employee Monitoring Software
Benefits of Employee Monitoring Software
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data Migration
 
How To Build a Successful SaaS Design.pdf
How To Build a Successful SaaS Design.pdfHow To Build a Successful SaaS Design.pdf
How To Build a Successful SaaS Design.pdf
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 

Java threads

  • 2. INTRODUCTION • A thread is an independent path of execution within a program. • Many threads can run concurrently within a program. • Every thread in Java is created and controlled by the java.lang.Thread class. • A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.
  • 3. • Thread is a lightweight sub process • 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. • Thread is executed inside the process. There is context- switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads.
  • 4. Multitasking and Multithreading • Multitasking: – refers to a computer's ability to perform multiple jobs concurrently – more than one program are running concurrently, e.g., UNIX • Multithreading: – A thread is a single sequence of execution within a program – refers to multiple threads of control within a single program – each program can run multiple threads of control within it, e.g., Web Browser 4
  • 6. What are Threads Good For? • To maintain responsiveness of an application during a long running task • To enable cancellation of separable tasks • Some problems are intrinsically parallel • To monitor status of some resource (e.g., DB) • Some APIs and systems demand it (e.g., Swing) 6
  • 7. Advantage 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.
  • 8. Life cycle of a Thread The life cycle of the thread in java is controlled by JVM. The java thread states are as follows: – New – Runnable – Running – Non-Runnable (Blocked) – Terminated
  • 9.
  • 10. Life cycle of a Thread (Contd) • 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.
  • 11. Daemon thread • Daemon thread is a low priority thread (in context of JVM) that runs in background to perform tasks such as garbage collection. • JVM terminates itself when all user threads (non-daemon threads) finish their execution, JVM does not care whether Daemon thread is running or not,
  • 12. Thread Priority • When a Java thread is created, it inherits its priority from the thread that created it. • You can modify a thread’s priority at any time after its creation using the setPriority method. • Thread priorities are integers ranging between • MIN_PRIORITY (1) • NORM_PRIORITY (5) • MAX_PRIORITY (10)
  • 13. Creating Threads • There are two ways to create our own Thread object – By extending Thread class – By implementing Runnable interface. • In both cases the run() method should be implemented
  • 14. Commonly used Constructors of Thread class • Thread() • Thread(String name) • Thread(Runnable r) • Thread(Runnable r,String name)
  • 15. Extending Thread SYNTAX class Mythread extends Thread { public void run(){ -------------- -------------- -------------- -------------- } } PROGRAM 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...
  • 16. Thread Methods void start() – Creates a new thread and makes it runnable – This method can be called only once void run() – The new thread begins its life inside this method void stop() (deprecated) – The thread is being terminated
  • 17. Thread Methods void yield() – Causes the currently executing thread object to temporarily pause and allow other threads to execute – Allow only threads of the same priority to run void sleep(int m) or sleep(int m, int n) – The thread sleeps for m milliseconds, plus n nanoseconds
  • 18. Thread Methods • public void start() • public void run() • public final void setName(String name) • public final void setPriority(int priority) • public final void setDaemon(boolean on) • public final void join(long millisec) • public void interrupt() • public final boolean isAlive() • public static void yield() • public static void sleep(long millisec) • public static boolean holdsLock(Object x) • public static Thread currentThread() • public static void dumpStack()
  • 19. Implementing Runnable class Multi3 implements Runnable{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi3 m1=new Multi3(); Thread t1 =new Thread(m1); t1.start(); } } Output: thread is running...