SlideShare a Scribd company logo
2
Most read
3
Most read
8
Most read
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
Java threads
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 (20)

PPT
Abstract class in java
Lovely Professional University
 
PPT
Exception Handling in JAVA
SURIT DATTA
 
PPTX
Constructor in java
Pavith Gunasekara
 
PPTX
This keyword in java
Hitesh Kumar
 
PPT
Java Threads
M Vishnuvardhan Reddy
 
PPS
Java Exception handling
kamal kotecha
 
PPTX
Inheritance in java
RahulAnanda1
 
PPTX
Inheritance in java
Tech_MX
 
PPTX
Presentation on-exception-handling
Nahian Ahmed
 
PPTX
Arrays in Java
Abhilash Nair
 
PDF
Java thread life cycle
Archana Gopinath
 
PPTX
OOPS In JAVA.pptx
Sachin33417
 
PPTX
Control statements in java
Madishetty Prathibha
 
PPT
Java interfaces
Raja Sekhar
 
PPTX
Static Members-Java.pptx
ADDAGIRIVENKATARAVIC
 
PPT
Collection Framework in java
CPD INDIA
 
PPTX
Control structures in java
VINOTH R
 
PDF
Class and Objects in Java
Spotle.ai
 
PPTX
Java abstract class & abstract methods
Shubham Dwivedi
 
Abstract class in java
Lovely Professional University
 
Exception Handling in JAVA
SURIT DATTA
 
Constructor in java
Pavith Gunasekara
 
This keyword in java
Hitesh Kumar
 
Java Threads
M Vishnuvardhan Reddy
 
Java Exception handling
kamal kotecha
 
Inheritance in java
RahulAnanda1
 
Inheritance in java
Tech_MX
 
Presentation on-exception-handling
Nahian Ahmed
 
Arrays in Java
Abhilash Nair
 
Java thread life cycle
Archana Gopinath
 
OOPS In JAVA.pptx
Sachin33417
 
Control statements in java
Madishetty Prathibha
 
Java interfaces
Raja Sekhar
 
Static Members-Java.pptx
ADDAGIRIVENKATARAVIC
 
Collection Framework in java
CPD INDIA
 
Control structures in java
VINOTH R
 
Class and Objects in Java
Spotle.ai
 
Java abstract class & abstract methods
Shubham Dwivedi
 

Similar to Java threads (20)

PPTX
U4 JAVA.pptx
madan r
 
PPTX
Module 4 - Part 4 - Multithreaded Programming.pptx
FahmaFamzin
 
PPT
web programming-Multithreading concept in Java.ppt
mcjaya2024
 
PPTX
Multithreading in java
Lovely Professional University
 
PPTX
Lec 1.10 Object Oriented Programming
Badar Waseer
 
PPTX
Object-Oriented-Prog_MultiThreading.pptx
NasreenTaj20
 
PPTX
econtent thread in java.pptx
ramyan49
 
PPTX
Multi-Threading in Java power point presenetation
AshokRachapalli1
 
PPTX
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
PPTX
Threads in Java
HarshaDokula
 
PDF
Java threading
Chinh Ngo Nguyen
 
PPTX
Thread
sajidhuseyin
 
PPTX
Thread
Sajid Hussain
 
PDF
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
universitypresidency
 
PPT
BCA MultiThreading.ppt
sarthakgithub
 
PPT
Threads in java, Multitasking and Multithreading
ssusere538f7
 
PPTX
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
PPTX
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
PPTX
Multithreading in java
Kavitha713564
 
PPTX
Multithreading in java
Kavitha713564
 
U4 JAVA.pptx
madan r
 
Module 4 - Part 4 - Multithreaded Programming.pptx
FahmaFamzin
 
web programming-Multithreading concept in Java.ppt
mcjaya2024
 
Multithreading in java
Lovely Professional University
 
Lec 1.10 Object Oriented Programming
Badar Waseer
 
Object-Oriented-Prog_MultiThreading.pptx
NasreenTaj20
 
econtent thread in java.pptx
ramyan49
 
Multi-Threading in Java power point presenetation
AshokRachapalli1
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
Threads in Java
HarshaDokula
 
Java threading
Chinh Ngo Nguyen
 
Thread
sajidhuseyin
 
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
universitypresidency
 
BCA MultiThreading.ppt
sarthakgithub
 
Threads in java, Multitasking and Multithreading
ssusere538f7
 
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
Multithreading in java
Kavitha713564
 
Multithreading in java
Kavitha713564
 
Ad

More from Prabhakaran V M (8)

PDF
Strings in python
Prabhakaran V M
 
PDF
Operators in python
Prabhakaran V M
 
PDF
Algorithmic problem solving
Prabhakaran V M
 
PDF
Open mp directives
Prabhakaran V M
 
PDF
Xml schema
Prabhakaran V M
 
PDF
Html 5
Prabhakaran V M
 
PDF
Introduction to Multi-core Architectures
Prabhakaran V M
 
PDF
Applets
Prabhakaran V M
 
Strings in python
Prabhakaran V M
 
Operators in python
Prabhakaran V M
 
Algorithmic problem solving
Prabhakaran V M
 
Open mp directives
Prabhakaran V M
 
Xml schema
Prabhakaran V M
 
Introduction to Multi-core Architectures
Prabhakaran V M
 
Ad

Recently uploaded (20)

PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
NEW-Viral>Wondershare Filmora 14.5.18.12900 Crack Free
sherryg1122g
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
NEW-Viral>Wondershare Filmora 14.5.18.12900 Crack Free
sherryg1122g
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 

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
  • 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...