Chapter 2 - Multi Threading
Chapter 2 - Multi Threading
Mettu University
Department of Information Technology
3rd Year
Advanced Programming – Chapter 2
Introduction
Example:
• one program can display an animation on the screen
while another may build the next animation to be
displayed. This is something similar to dividing a task
into subtasks and assigning them to different people
for execution independently and simultaneously.
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
Concurrency vs. Parallelism
CPU CPU1 CPU2
Single threaded Vs Multithreaded
Single-Threaded:
A Thread is similar to a program that has a single
flow of control. It has a beginning, a body and an
end. And executes commands sequentially. In fact
all main programs in our earlier examples can be
called single-threaded programs.
Multithreading:
Java enable us to use multiple flows of control in
developing programs. Each flow of control may be
thought of as a separate tiny program known as a
thread that runs in parallel to others.
Cont..
Why do we need threads?
• To enhance parallel processing
• To increase response to the user
• To utilize the idle time of the CPU
• Prioritize your work depending on priority
Example
• Consider a simple web server
• The web server listens for request and serves it
• If the web server was not multithreaded, the
requests processing would be in a queue, thus
increasing the response time and also might hang
the server if there was a bad request.
• By implementing in a multithreaded environment, the
web server can serve multiple request
simultaneously thus improving response time
Creating Threads
• There are two ways to create our own Thread object
1. Sub classing or extending a Thread class and
instantiating a new object of that class
2. Implementing the Runnable interface
• In both cases the run() method should be implemented
Extending Thread
public class ChildThread extends Thread {
public void run () {
for (int i = 1; i <= 100; i++) {
System.out.println(“---”);
}
}
}
Implementing Runnable
public class ChildRunnableThread implements Runnable {
public void run () {
for (int i = 1; i <= 100; i++) {
System.out.println (“***”);
}
}
}
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
Starting New Thread
Example:
Case 1: If the class extends Thread
ChildThread aThread = new ChildThread( );
aThread.start( ); // Invokes run( )
method.
1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
stop
start
Active Thread
stop
Dead
Running Runnable
yield
Killed
suspend Thread
resume
sleep stop
notify
wait
Blocked Idle Thread
(Not Runnable)
Life Cycle of a Thread
Newborn State:
Newborn
Runnable Cont..
Dead State
State
Life Cycle of a Thread
Runnable State:
yield
… …
Runnable
Running Thread
Thread Cont..
Life Cycle of a Thread
Running State:
Running means that the processor has given its time
to the thread for its execution. The Thread runs
until it relinquishes control on its own or it is
preempted by a higher priority thread.
A running thread may relinquish its control in one
of the following situations.
It has been suspended using suspend( ) method. A
suspended thread can be revived by using the resume( )
method.
Suspend
resume
after t
It has been told to wait until some event occurs. This is done using the
wait( ) method. The thread can be scheduled to run using the notify( )
method.
wait
notify
Dead State:
Every thread has a life cycle. A running thread ends
its life when it has completed executing its run( )
method. It’s a natural death.
However, we can kill it by sending the stop message
to it at any state thus causing a premature death to
it.
Cont..
Example
public class PrintThread1 extends Thread {
String name;
public PrintThread1(String name) {
this.name = name;
}
public void run() {
for (int i=1; i<100 ; i++) {
try {
sleep((long)(Math.random() * 100));
} catch (InterruptedException ie) { }
System.out.print(name);
}
}
Example (cont)
a.start();
b.start();
}
}
Stopping & Blocking Thread
Stopping Thread:
Blocking a Thread:
A thread can also be temporarily suspended or blocked from
entering in to the runnable and subsequently running state by using
either of the following thread methods:
Stopping & Blocking Thread
Blocking a Thread:
A thread can also be temporarily suspended or blocked from
entering in to the runnable and subsequently running state by using
either of the following thread methods:
Note: These methods cause the thread to go into the blocked (or not-
runnable) state.
the tread will return to the runnable state when the specified time is
elapsed in the case of sleep( ).
The resume( ) method is invoked in the case of suspend( ).
The notify( ) method is called in the case of wait( ).
Thread Exceptions
Syntax:
ThreadName.setPriority(intNumber);
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Synchronization
Consider the Example, one thread may try to read a record from a file
while another is still writing to the same file. Depending on the situation,
we may get strange results.
Java enables us to overcome this problem using a technique known as
synchronization.
Example Coding :
synchronized void update( )
{
…….
……
}
When we declare a method synchronized, java creates a “monitor” and
hands it over to the thread that calls the method first time. As long as the
thread holds the monitor, no other thread can enter the synchronized
section of code.
Daemon Threads
• Daemon threads are “background” threads, that provide
services to other threads, e.g., the garbage collection
thread
• The Java VM will not exit if non-Daemon threads are
executing
• The Java VM will exit if only Daemon threads are
executing
• Daemon threads die when the Java VM exits
• Q: Is the main thread a daemon thread?
• A: No
Daemon Thread
• To Check the Current Daemon status:
threadObject.isDaemon();
• To set the thread to Daemon thread:
threadObject.setDaemon(true);