SlideShare a Scribd company logo
Java 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.
Multithreading refers to multiple threads of control
within a single program each program can run
multiple threads of control within it, e.g., Web
Browser
Concurrency vs. Parallelism
CPU CPU1 CPU2
Threads and Processes
CPU
Process 1 Process 3
Process 2 Process 4
main
run
GC
Advantages of multithreading
1. Reduces the computation time.
2. Improves performance of an application.
3. Threads distribute the same address space so it
saves the memory.
4. Context switching between threads is usually
less costly than between processes.
5. Cost of communication between threads is
comparatively low.
Applications
 When we execute an application:
1. The JVM creates a Thread object whose task is
defined by the main() method
2. The JVM starts the thread
3. The thread executes the statements of the
program one by one
4. After executing all the statements, the method
returns and the thread dies
7
A single threaded program
class ABC
{
….
public void main(..)
{
…
..
}
}
begin
body
end
A Multithreaded Program
Main Thread
Thread A Thread B Thread C
start start
start
Threads may switch or exchange data/results
Web/Internet Applications:
Serving Many Users Simultaneously
Internet
Server
PC client
Local Area Network
PDA
10
Threading Mechanisms...
1. Create a class that extends the Thread class
2. Create a class that implements the Runnable
interface
In both cases the run() method should be implemented
1st method: Extending Thread class
 Threads are implemented as objects that contains a
method called run()
class MyThread extends Thread
{
public void run()
{
// thread body of
execution
}
}
 Create a thread:
MyThread thr1 = new MyThread();
 Start Execution of threads:
class MyThread extends Thread {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx1 {
public static void main(String [] args ) {
MyThread t = new MyThread();
t.start();
}
}
2nd method:
Threads by implementing Runnable interface
class MyThread implements Runnable
{
public void run()
{
// thread body of execution
}
}
 Creating Object:
MyThread myObject = new MyThread();
 Creating Thread Object:
Thread thr1 = new Thread( myObject );
 Start Execution:
thr1.start();
A Runnable Object
 When running the Runnable object, a Thread
object is created from the Runnable object
 The Thread object’s run() method calls the
Runnable object’s run() method
 Allows threads to run inside any object, regardless
of inheritance
An example
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx2 {
public static void main(String [] args ) {
MyThread o=new MyThread();
Thread t = new Thread(o);
t.start();
}
}
A Program with Three Java Threads
Write a program that creates 3 threads
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("t From ThreadA: i= "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread {
public void run()
{
for(int i=6;i<=10;i++)
{
System.out.println("t From ThreadB: i= "+i);
}
System.out.println("Exit from B");
}
}
class C extends Thread {
public void run()
{
for(int i=11;i<=15;i++) {
System.out.println("t From ThreadC: i= "+i);
}
System.out.println("Exit from C");
}
}
class ThreadTest
{
public static void main(String args[])
{
A obA=new A();
B obB=new B();
C obC=new C();
obA.start();
obB.start();
obC.start();
Thread Methods
void start()
Creates a new thread and makes it runnable
This method can be called only once.
aThread.start()
void run()
The new thread begins its life inside this
method
Stopping a Thread
Whenever we want to stop a thread from
running further, call stop() method
aThread.stop()
This method causes the thread to move to
dead state.
The stop may used when the premature
death of thread is desired.
Blocking a Thread
A thread can also be temporarily suspended or
blocked from entering into the runnable and
running state by using following methods.
sleep() :blocked for specified time
suspend() :blocked until further orders ( resume() )
wait() :blocked until certain conditions occurs
(notify())
These methods causes the thread to go into
blocked state.
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.
Life Cycle of Thread
 During Life time of a thread there are many states it
can enter.
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
A thread is always in one of these five states.
It can move from one state to another via a variety
of ways.
Thread State Diagram
Newborn
Thread
Dead Thread
Runnable
new ThreadExample();
run()
method
returns
Blocked
wait()
sleep()
Suspend()
thread.start();
Running
Active
Thread
yield
resume()
notify()
stop()
stop()
Idle Thread
Not Runnable
Running
Newborn State
Dead Thread
Runnable
start();
When we create a thread object, the thread is born
and is said to be in newborn state.
The thread is not yet scheduled for running. At this
state we can do only the following things
Newborn
stop();
Runnable State
 Means that thread is ready for execution and is
waiting for the availability of the processor.
 That is , thread has joined the waiting queue.
 Threads with equal priority are scheduled in round
robin fashion. i.e. (FCFS)
 However, a thread can relinquish control to another
thread by using yield() method.
Runnable Threads
Running Thread
yield()
Running State
 Running means that processor has given its time to
the thread for its execution.
 The thread runs until it relinquishes control on its
own or it is interrupted by higher priority thread.
 The running thread may relinquish its control in one
of the following situations.
1. It has been suspended using suspend() method.
2. It has been made to sleep
3. It has been told to wait until some event occurs.
1. It has been suspended using suspend() method.
Running
suspend()
Running
Running
sleep(t)
resume()
after(t)
wait
notify
Runnable
Runnable
Runnable
Suspended
Suspended
Waiting
2. It has been made to sleep
3. It has been told to wait until some event occurs
Blocked State
 A thread is blocked when it is prevented from entering
into the runnable and running state.
 This happens when thread is suspended, sleeping, or
waiting in order to satisfy certain requirements.
 A blocked thread is “not runnable” but not dead and
therefor fully qualified to run again.
Dead State
 Every thread has life cycle. A thread ends its life when
it has completed its execution. It is natural death.
 However we can kill it by sending the stop message. A
thread can be killed as soon as it born.
Demo
ThreadMethods
Scheduling Threads
I/O operation completes
start()
Currently executed
thread
Ready queue
• Waiting for I/O operation to be completed
• Waiting to be notified
• Sleeping
• Waiting to enter a synchronized section
Newly created
threads
Preemptive Scheduling
Preemptive scheduling – the thread scheduler
preempts (pauses) a running thread to allow
different threads to execute.
Nonpreemptive scheduling – the scheduler
never interrupts a running thread.
Thread Priority
Every thread has a priority.
When a thread is created, it inherits the
priority of the thread that created it.
The priority values range from 1 to 10, in
increasing priority.
Thread Priority (cont.)
The priority can be adjusted subsequently using
the setPriority() method
Threadname.setPriority(intNumber);
The priority of a thread may be obtained using
getPriority()
 Priority constants are defined:
MIN_PRIORITY=1
MAX_PRIORITY=10
NORM_PRIORITY=5
The main thread is
created with priority
NORM_PRIORITY
Synchronization
In Java, the threads are executed separately to
each other. These threads are called as
asynchronous.
But what if two threads try to use same data?
For example, one thread may try to read
record from a file while another is still writing
to same file.
Depending on the situation we may get
strange results.
Synchronization
 Java enables us to overcome this using synchronization.
 Keyword synchronized helps to solve such problems.
 The method that will read the file and method that will
update file may be declared as synchronized.
synchronized void update()
{
…….
}
Synchronization
Java creates a “monitor” and hands it to the
thread that calls the method first time.
As long as the method holds the monitor, no
other thread can enter the synchronized section
of code.
A monitor is like a key and the thread is that
holds the key can only open the lock.
Whenever a thread has completed its work it
will handover the monitor the next thread.
Demo
SynThread1.java

More Related Content

PPTX
econtent thread in java.pptx
PPT
Java And Multithreading
PDF
Multithreading Introduction and Lifecyle of thread
PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
PPTX
multithreading to be used in java with good programs.pptx
PPTX
Multithreading in java
PPTX
Multithreading in java
PPTX
multithreading,thread and processinjava-210302183809.pptx
econtent thread in java.pptx
Java And Multithreading
Multithreading Introduction and Lifecyle of thread
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
multithreading to be used in java with good programs.pptx
Multithreading in java
Multithreading in java
multithreading,thread and processinjava-210302183809.pptx

Similar to MSBTE Computer Engineering JPR java. multi. threading.pptx (20)

PPT
Threads in java, Multitasking and Multithreading
PPTX
unit3multithreadingppt-copy-180122162204.pptx
PPTX
unit3 Exception Handling multithreadingppt.pptx
PPT
Md09 multithreading
PPTX
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
PPT
Session 7_MULTITHREADING in java example.ppt
PPTX
Chap3 multi threaded programming
PPTX
Multithreading
PPTX
Multithreading in java
PPTX
Multithreadingppt.pptx
DOCX
Threadnotes
PDF
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
PPTX
Multi-threaded Programming in JAVA
PPTX
Threading concepts
PPTX
Multithreading in java
PPTX
PPTX
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
PPT
Multithreading
 
PPTX
MULTI THREADING IN JAVA
PPTX
Multithreading programming in java
Threads in java, Multitasking and Multithreading
unit3multithreadingppt-copy-180122162204.pptx
unit3 Exception Handling multithreadingppt.pptx
Md09 multithreading
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
Session 7_MULTITHREADING in java example.ppt
Chap3 multi threaded programming
Multithreading
Multithreading in java
Multithreadingppt.pptx
Threadnotes
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
Multi-threaded Programming in JAVA
Threading concepts
Multithreading in java
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Multithreading
 
MULTI THREADING IN JAVA
Multithreading programming in java
Ad

Recently uploaded (20)

PPTX
Lecture Notes Electrical Wiring System Components
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
web development for engineering and engineering
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
Welding lecture in detail for understanding
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
OOP with Java - Java Introduction (Basics)
PDF
Digital Logic Computer Design lecture notes
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
DOCX
573137875-Attendance-Management-System-original
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Lecture Notes Electrical Wiring System Components
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Internet of Things (IOT) - A guide to understanding
web development for engineering and engineering
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Welding lecture in detail for understanding
UNIT 4 Total Quality Management .pptx
OOP with Java - Java Introduction (Basics)
Digital Logic Computer Design lecture notes
Automation-in-Manufacturing-Chapter-Introduction.pdf
573137875-Attendance-Management-System-original
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Foundation to blockchain - A guide to Blockchain Tech
Operating System & Kernel Study Guide-1 - converted.pdf
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Ad

MSBTE Computer Engineering JPR java. multi. threading.pptx

  • 2. 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. Multithreading 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. Threads and Processes CPU Process 1 Process 3 Process 2 Process 4 main run GC
  • 5. Advantages of multithreading 1. Reduces the computation time. 2. Improves performance of an application. 3. Threads distribute the same address space so it saves the memory. 4. Context switching between threads is usually less costly than between processes. 5. Cost of communication between threads is comparatively low.
  • 6. Applications  When we execute an application: 1. The JVM creates a Thread object whose task is defined by the main() method 2. The JVM starts the thread 3. The thread executes the statements of the program one by one 4. After executing all the statements, the method returns and the thread dies
  • 7. 7 A single threaded program class ABC { …. public void main(..) { … .. } } begin body end
  • 8. A Multithreaded Program Main Thread Thread A Thread B Thread C start start start Threads may switch or exchange data/results
  • 9. Web/Internet Applications: Serving Many Users Simultaneously Internet Server PC client Local Area Network PDA
  • 10. 10 Threading Mechanisms... 1. Create a class that extends the Thread class 2. Create a class that implements the Runnable interface In both cases the run() method should be implemented
  • 11. 1st method: Extending Thread class  Threads are implemented as objects that contains a method called run() class MyThread extends Thread { public void run() { // thread body of execution } }  Create a thread: MyThread thr1 = new MyThread();  Start Execution of threads:
  • 12. class MyThread extends Thread { public void run() { System.out.println(" this thread is running ... "); } } class ThreadEx1 { public static void main(String [] args ) { MyThread t = new MyThread(); t.start(); } }
  • 13. 2nd method: Threads by implementing Runnable interface class MyThread implements Runnable { public void run() { // thread body of execution } }  Creating Object: MyThread myObject = new MyThread();  Creating Thread Object: Thread thr1 = new Thread( myObject );  Start Execution: thr1.start();
  • 14. A Runnable Object  When running the Runnable object, a Thread object is created from the Runnable object  The Thread object’s run() method calls the Runnable object’s run() method  Allows threads to run inside any object, regardless of inheritance
  • 15. An example class MyThread implements Runnable { public void run() { System.out.println(" this thread is running ... "); } } class ThreadEx2 { public static void main(String [] args ) { MyThread o=new MyThread(); Thread t = new Thread(o); t.start(); } }
  • 16. A Program with Three Java Threads Write a program that creates 3 threads class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("t From ThreadA: i= "+i); } System.out.println("Exit from A"); } }
  • 17. class B extends Thread { public void run() { for(int i=6;i<=10;i++) { System.out.println("t From ThreadB: i= "+i); } System.out.println("Exit from B"); } }
  • 18. class C extends Thread { public void run() { for(int i=11;i<=15;i++) { System.out.println("t From ThreadC: i= "+i); } System.out.println("Exit from C"); } }
  • 19. class ThreadTest { public static void main(String args[]) { A obA=new A(); B obB=new B(); C obC=new C(); obA.start(); obB.start(); obC.start();
  • 20. Thread Methods void start() Creates a new thread and makes it runnable This method can be called only once. aThread.start() void run() The new thread begins its life inside this method
  • 21. Stopping a Thread Whenever we want to stop a thread from running further, call stop() method aThread.stop() This method causes the thread to move to dead state. The stop may used when the premature death of thread is desired.
  • 22. Blocking a Thread A thread can also be temporarily suspended or blocked from entering into the runnable and running state by using following methods. sleep() :blocked for specified time suspend() :blocked until further orders ( resume() ) wait() :blocked until certain conditions occurs (notify()) These methods causes the thread to go into blocked state.
  • 23. 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.
  • 24. Life Cycle of Thread  During Life time of a thread there are many states it can enter. 1. Newborn state 2. Runnable state 3. Running state 4. Blocked state 5. Dead state A thread is always in one of these five states. It can move from one state to another via a variety of ways.
  • 25. Thread State Diagram Newborn Thread Dead Thread Runnable new ThreadExample(); run() method returns Blocked wait() sleep() Suspend() thread.start(); Running Active Thread yield resume() notify() stop() stop() Idle Thread Not Runnable Running
  • 26. Newborn State Dead Thread Runnable start(); When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state we can do only the following things Newborn stop();
  • 27. Runnable State  Means that thread is ready for execution and is waiting for the availability of the processor.  That is , thread has joined the waiting queue.  Threads with equal priority are scheduled in round robin fashion. i.e. (FCFS)  However, a thread can relinquish control to another thread by using yield() method. Runnable Threads Running Thread yield()
  • 28. Running State  Running means that processor has given its time to the thread for its execution.  The thread runs until it relinquishes control on its own or it is interrupted by higher priority thread.  The running thread may relinquish its control in one of the following situations. 1. It has been suspended using suspend() method. 2. It has been made to sleep 3. It has been told to wait until some event occurs.
  • 29. 1. It has been suspended using suspend() method. Running suspend() Running Running sleep(t) resume() after(t) wait notify Runnable Runnable Runnable Suspended Suspended Waiting 2. It has been made to sleep 3. It has been told to wait until some event occurs
  • 30. Blocked State  A thread is blocked when it is prevented from entering into the runnable and running state.  This happens when thread is suspended, sleeping, or waiting in order to satisfy certain requirements.  A blocked thread is “not runnable” but not dead and therefor fully qualified to run again. Dead State  Every thread has life cycle. A thread ends its life when it has completed its execution. It is natural death.  However we can kill it by sending the stop message. A thread can be killed as soon as it born. Demo ThreadMethods
  • 31. Scheduling Threads I/O operation completes start() Currently executed thread Ready queue • Waiting for I/O operation to be completed • Waiting to be notified • Sleeping • Waiting to enter a synchronized section Newly created threads
  • 32. Preemptive Scheduling Preemptive scheduling – the thread scheduler preempts (pauses) a running thread to allow different threads to execute. Nonpreemptive scheduling – the scheduler never interrupts a running thread.
  • 33. Thread Priority Every thread has a priority. When a thread is created, it inherits the priority of the thread that created it. The priority values range from 1 to 10, in increasing priority.
  • 34. Thread Priority (cont.) The priority can be adjusted subsequently using the setPriority() method Threadname.setPriority(intNumber); The priority of a thread may be obtained using getPriority()  Priority constants are defined: MIN_PRIORITY=1 MAX_PRIORITY=10 NORM_PRIORITY=5 The main thread is created with priority NORM_PRIORITY
  • 35. Synchronization In Java, the threads are executed separately to each other. These threads are called as asynchronous. But what if two threads try to use same data? For example, one thread may try to read record from a file while another is still writing to same file. Depending on the situation we may get strange results.
  • 36. Synchronization  Java enables us to overcome this using synchronization.  Keyword synchronized helps to solve such problems.  The method that will read the file and method that will update file may be declared as synchronized. synchronized void update() { ……. }
  • 37. Synchronization Java creates a “monitor” and hands it to the thread that calls the method first time. As long as the method holds the monitor, no other thread can enter the synchronized section of code. A monitor is like a key and the thread is that holds the key can only open the lock. Whenever a thread has completed its work it will handover the monitor the next thread. Demo SynThread1.java