Faculty of
Computing &
Software
Eng’g
Program:
Information
Advanced Programming
Technology
G3 IT
(Regular)
Instructor:
Addisu M. (Asst.
Prof)
2
Ch ne
Multithreading
rO
ap
te
Outline
Threads vs. process
Thread States
Advanced Programming
Multiple threads
Thread Priorities and Scheduling
Synchronization
3
Introduction
Human body performs variety of operations in
parallel
Computers also too, can perform operations
concurrently
Advanced Programming
Java is a multithreaded programming language
possible to develop multithreaded program using
Java
Only computers that have multiple processors
can truly execute multiple instructions
concurrently 4
Introduction
Process & Thread - two basic units of program
execution Code Data
Process components: Process Status
Resource
program (code) to be executed
data on which program will execute
Advanced Programming
resources required by the program Abstract Machine Environment
status of the process execution
Program and Process – distinction?
Program is a static entity made up of program
statements
Process is a dynamic entity that executes a
program on a particular set of data
define the run-time behavior 5
Introduction
Process & Thread - two basic units of program
execution
Thread: lightweight sub-process, smallest unit of
processing
requires less resources to create and exists in
Advanced Programming
the process
independent - if there occurs exception in one
thread, it doesn't affect other threads
shares process resources (memory), which is
visible to all threads in a multi-threaded
program
Unlike many other computer languages, Java
provides built-in support for multithreaded 6
Multitasking
In computing, multitasking – a method by which
multiple tasks or processes, share common processing
resources such as CPU
Each of these programs has at least one thread within
it - single-threaded process:
Advanced Programming
process begins execution at a well-known point -
main
In Java, C# or C++, process begins execution at the first
statement of the function called main()
While executing, process has access to certain data –
local, global, static, etc
Multitasking – process of executing multiple tasks
simultaneously
can be achieved in two ways: 7
Multitasking
Process-based Multitasking
(Multiprocessing)
Each process has an address in memory
In other words, each process allocates a separate
memory area
Advanced Programming
process is heavyweight
Cost of communication between the process is high
Switching from one process to another requires some
time for saving & loading registers, memory maps,
updating lists, etc
Thread-based Multitasking (Multithreading)
Threads share the same address space
Thread is lightweight 8
Process vs Thread
Process Thread
a program in execution a subset (part) of the process
smallest part of the process that can
consists of multiple
execute concurrently with other
threads
parts of process
heavyweight program lightweight program
Advanced Programming
has its own address space uses the process’s address space
Each process allocates a and shares it with the other threads
separate memory area of that process
can communicate with can communicate with other thread
other process by using (of the same process) directly by
interprocess using methods like wait(), notify(),
communication notifyAll()
does not have control over 9
Multithreading
Multithreading – technique in which a program
(process) is divided into two or more subprograms
(subprocesses), each of which can perform different
tasks simultaneously
Each subprogram of a program is called thread in Java
Advanced Programming
E.g., program has 3 threads, one and two (ThreadA &
ThreadB) other
When program
Two contains >1 thread, CPU canfrom the main
threads are created and started
switch b/n two threads to execute them at
thread
same time
Once initiated by theismain
Switching b/n 2 threads knownthread, ThreadA and
ThreadB
as Contextrun simultaneously and share the resources
Switch
together
Switching occurs so fast that it appears to
users that all threads are being executed at
the same time 10
Multithreading
Multithreading - improves performance of CPU by
maximum utilization and keeping the idle time of CPU
to minimum
each thread is assigned a single task to perform and
executes independently
If an exception occurs in one thread, it does not affect
Advanced Programming
other threads during the execution
For example,
One thread - read data,
Second thread - process it, and
Third thread - write it
Thus, improves the overall performance of an application
A process that is
made of one thread is known as single- threaded 11
Multithreading
Multithreading – a conceptual programming
paradigm where a program (process) is divided into
sub-processes that can run concurrently and each
part can handle different task at the same time
making optimal use of the available resources
Advanced Programming
Multiprocessing and multithreading, both are used to
achieve multitasking
Java multithreading is mostly used
in games, animation, etc
E.g, one subprogram can be used
for typing while the another may
used to check spelling error
12
Multithreading
In multithreading program, threads have the ff
properties:
begin execution at a predefined, well-known location
For one of the threads in the program, that location is the
main() method; for the rest of the threads, it is a
particular location the programmer decides on when
Advanced Programming
the code is written
executes code in an ordered, predefined sequence
executes its code independently of the other threads
Thread is executed inside the process
There is context-switching between the
threads
There can be multiple processes inside 13
Multithreading
Advantage
1. In a multithreaded application program, different
parts of the application are executed by different
threads. The entire application does not stop even
if an exception occurs in any of the threads. It
Advanced Programming
does not affect other threads during the execution
of the application.
2. Different threads are allotted to different
processors and each thread is executed in
different processors in parallel.
3. Multithreading helps to reduce computation time.
4. Multithreading improves the performance of the 14
Multithreading
Advantage
6. Multithreaded program makes maximum
utilization of CPU and keeping the idle time of CPU
to minimum.
7. Context switching from one thread to another
Advanced Programming
thread is less expensive than between processes
Drawbacks
1. Increased complexity.
2. Synchronization of shared resources.
3. In the multithreading programming concept,
debugging is difficult. At times, result is
unpredictable. 15
Multithreading
Example: thread-based multithreading in Java
A word processing program that checks the spelling of
words in a document while writing the document
Program is divided into two parts, two separate
blocks of code/methods that can perform two different
Advanced Programming
tasks
Hence, a processor will create two separate threads to
execute these two parts simultaneously
Each thread acts as an individual process
that will execute a separate block of code
Processor has two threads that will
perform two different tasks at a time
16
Life Cycle of Thread
goes through various stages in its life cycle,
includes:
Newborn state
Runnable state
Running state
Advanced Programming
Blocked state
Dead state
17
Life Cycle of Thread
Newborn State
When a thread object is created a new thread is
born
thread is not yet scheduled for running
remains in this state till the program starts the
Advanced Programming
thread
At this state, we can do only one of the following:
Schedule it for running
Thread using
newThread start()
= new method
Thread(this,
Kill it using“threadName”)
stop() method
Syntax: Newb
start oarn stop
Runnabl
e
Dead 18
Life Cycle of Thread
Runnable State
When start method is invoked, JVM calls run
method
instance of the thread is invoked with a start method
thread control is given to scheduler to finish the
Advanced Programming
execution
depends on the scheduler, whether to run the thread
ready to execute but not allocated to
processor (waiting for CPU time), because the
processor may be busy with another operation
has joined the queue
Running State
Thread is executing 19
Life Cycle of Thread
Blocked State
happens when thread is suspended, sleeping, or
waiting in order to satisfy certain requirements
(waiting for any I/O operations)
prevented to entering into the runnable and running state
Example: happen when multiple threads are trying to
Advanced Programming
access a synchronized resource
achieved when we invoked suspend() or wait()
method
Eg.: [Link](500); or [Link](); or
[Link]();
Dead State
running thread ends its life when it has completed
executing its run() method - natural death 20
Main Thread
Main thread – most
important part of any
application
Executed whenever a
Java program starts
Every program must
Advanced Programming
contain it for its execution
to take place
we can create child
threads through main
thread and start them
last thread to finish the
execution i.e., terminates
the program 21
Main Thread
public class Worker implements Runnable{
public static void main (String[] args){
[Link](“Currently running on
the main thread, " +
"the id is: " + [Link]().getId());
Worker worker = new Worker();
Advanced Programming
Thread thread = new Thread(worker);
[Link]();
}
@Override
public void run(){
[Link](“Currently running on a separate thre
ad, " +
"the id is: " + [Link]().getId());
Currently running on the main thread, the id is: 1
Output:
}
Currently running on a separate thread, the id is: 9
} 22
Thread Class
every Java program has at least one thread called
main thread
When program starts, main thread starts running
immediately
Although there are so many other java threads
Advanced Programming
running in background like memory management,
system management, signal processing etc
But from application point of view - main is the
first java thread and we can create multiple
threads from it
Multithreading refers to two or more threads
executing concurrently in a single program
A computer single core processor can execute 23
Thread Class
Apart from this main thread, we can also create
our own threads in a program that is called child
thread
Every child threads created from its main
(parent thread)
Advanced Programming
Thread class provides constructors and methods
to create and perform operations on a thread
In the most general sense, you can create a thread
Commonly Thread()
by instantiating
used an object of type Thread
Thread(String name)
Constructo
rs of Thread(Runnable r)
Thread Thread(Runnable r, String 24
Thread Class
Thread is a class found in [Link] package
Method Description
Thread Methods
run() Execution starts from this method
(entry point of the thread)
start() start a new thread of execution by
Advanced Programming
calling run() method
getName Retrieves the name of running thread
() in the current context in String format
sleep(int suspend the thread for mentioned time
sleeptim duration in argument (sleeptime in ms)
e)
join() wait till calling thread completes its
execution 25
Thread Class
Threads are implemented in the form of objects
run() and start() are two methods helps to
thread implementation
start(): used to begin the execution of a
thread
Advanced Programming
• When you call start(), it internally calls
the run() method.
• responsible for creating a new thread and then
executing run() method in that new thread
run(): contains the code that constitutes the
new thread's task
• When you call run() directly, it doesn't create a new 26
Thread Class
run() and start() are two methods helps to thread
class MyThread extends Thread {
implementation
public void run() {
[Link]("Thread is
public class Main {
running...");
} public static void main(String[] args) {
} MyThread thread = new MyThread();
Advanced Programming
[Link](); // create a new thread and call the
run() method
// [Link](); //just call the run() method in the
current thread
}
}
Two ways to create java thread
By extending thread class
By implementing Runnable 27
Create Thread
Extending Thread class
define a new thread by creating a subclass of Thread
and overriding its run() method to specify the code
that should be executed when the thread runs
invoke start() method which will internally execute
Advanced Programming
class Multi extends Thread {
run() method
public void run() {//to run thread
[Link](“First
Thread is running”);
}
public static void main(String
args[]){
Multi t1 = new Multi(); //
creating thread Output: First Thread is running 28
Create Thread
Extending Thread class
public class MyFirstThread extends Thread {
@Override
public void run() {
[Link]("I'm Thread! My name is "
+ getName());
Advanced Programming
}
} ublic class Main {
p
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
MyFirstThread thread = new MyFirstThread();
[Link]();
}
}
} 29
Create Thread
Extending Thread class
I'm Thread! My name is Thread-0
Output I'm Thread! My name is Thread-2
: I'm Thread! My name is Thread-4
I'm Thread! My name is Thread-1
I'm Thread! My name is Thread-3
Advanced Programming
Let's create 5 threads (MyFirstThread objects, which inherit
Thread) and start them by calling start() method on each object
After calling the start() method, the logic in the run() method
is executed.
Note: thread names are not in order. It's weird that they
weren't sequentially: Thread-0, Thread-1, Thread-2, and so on?
This is an example of a time when 'sequential' thinking doesn't
fit
The issue is that we've only provided commands to create & 30
Create Thread
Implementing Runnable Interface
We use inheritance when the class is inheriting some
other class
it can’t inherit thread at the same time because
multiple inheritance is not supported in java
So, if we are already extending class we can’t extend
Advanced Programming
thread class, but we can create thread with
Runnable Interface which can be implemented
Runnable interface has only one method, run(), that
is to be defined in the method with code to be
executed by thread
Then, instantiate an object and call start() method
Runnable runnable = new Runn
To create a thread using runnable, use the following
code- able();
Thread thread = new Thread(ru 31
Create Thread
Implementing Runnable Interface
class Multi3 implements Runnable {
public void run() { Example #1
[Link](“First Thread is
running”);
}
Advanced Programming
public static void main(String args[]){
Multi3 m1 = new Multi3(); // object initiated
for class
Thread t1 = new Thread(m1); // object
initiated for Thread
Output: First Thread is running
//Thread t1 = new Thread(new Multi3());
To execute [Link](); // run()
run() method, passmethod called
an instance through
of Multi3 tostart()
Thread in
its }constructor
} When thread is started it will call run() method of the Multi3 32
Create Thread
Implementing Runnable Interface
class Thread_Runnable implements Runnable {
public void run() { Example #2
for(int i=0; i < 5; i++){
[Link](“Child Thread : ” + i);
Advanced Programming
try{
[Link](50);
}
catch(InterruptedException ie){
[Link]("Child
thread interrupted! " + ie);
}
} 33
Create Thread
Implementing Runnable Interface
public static void main(String args[])
{ Output:
Thread_Runnable m = newMain thread: 10
Thread_Runnable(); Child
try{
Advanced Programming
thread: 0
for(int i = 10; i < 15; i++) Child
{ thread: 1
Main thread: 11
[Link]("Main thread: " + i);
[Link](1000);// Child
1000 ms = 1 sec thread: 2
} Child
} Exampl thread: 3 Main
catch(InterruptedException
e e){ thread: 12 34
Thread Class vs Runnable
Interface
Thread Class Runnable Interface
Each Thread creates its Each Thread creates its unique
unique object object
Advanced Programming
More memory consumption More memory consumption
A class extending Thread Along with Runnable a class can
class can’t extend any other implement any other interface
class (chance to extend)
Thread class is extended only Runnable is implemented only if
if there is a need of overriding there is a need of special run
other methods of it method 35
Thread Priorities
On a single CPU, threads actually run one at a time
in such a way as to provide an illusion of
concurrency
Execution of multiple threads on a single CPU, in some
order, is called scheduling
Thread priorities are used by the thread scheduler
Advanced Programming
to decide when each thread should be allowed to run
In practice, the amount of CPU time that a thread
gets often depends on several factors besides its
priority
For example, how an OS implements multitasking can
affect the relative availability of CPU time
Threads of equal priority will be given same treatment
by scheduler – (fixed priority scheduling algorithm)
This algorithm schedules threads based on their priority 36
Thread Priorities
To set the priority of thread at any time after its
creation, setPriority() method is used – method of
the Thread Class
[Link](int Number);
Number is integer value between 1 to 10, Here 1 is
Advanced Programming
minimum priority 10 is maximum priority.
Thread class defines few priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
In any Thread the default priority is
NORM_PRIORITY
getPriority() 37
Thread Priorities
public class test extends Thread{
public void run(){
[Link]("The control is under run function
now... ");
}
public static void main(String args[]){
test t1 = new test();
Advanced Programming
test t2 = new test();
[Link](2);
[Link](9);
[Link]("The priority assigned to thread t1 is:
" +
+ [Link]());
[Link]("The priority assigned to thread t2 is:
" + The priority assigned to thread t1
Output: is : 2
+ [Link]());
The priority assigned to thread t1 38
Synchronization
Concurrent access to shared data/resources
may result in data inconsistency
Maintaining data consistency requires
mechanisms to ensure the orderly execution
of cooperating processes (or threads)
Synchronization is a process of controlling
Advanced Programming
access of shared resources by the multiple
threads in such a manner that only one
thread can access a particular resource at a
time
multiple threads can work together without
creating any problems
synchronization process can achieve 39
Synchronization
In non synchronized multithreaded appln, it is
possible for one thread to modify a shared object
while another thread is in the process of using or
updating the object’s value
Advanced Programming
Synchronization prevents such type of data 40
Synchronization
Why do we need Synchronization?
Synchronization allows a programmer to perform
concurrent programming and prevents data
corruption int a =
Example: 5;
int b =
Advanced Programming
Suppose that two threads exist 4;
Thread 1 performs c = a + b whileint c =
Thread 2 performs c = c * a 0;
Initially c=0, what if thread 2 getsc =a+
b;cpu time before
thread 1? c=c*
value of c will remain zero despite a;
the multiplication
with a
original answer should have been 9=5+4 and then 41
Synchronization
Why do we need Synchronization?
Advanced Programming
42
Synchronization
When do we need synchronization?
When two or more threads work on the same
data simultaneously
Example: Two threads are trying to update the
same shared variable simultaneously:
Advanced Programming
result is unpredictable
result depends on which of the two threads was
the last one to change the value
competition of the threads for the variable is
called race condition
first thread is the one who wins the race to
update the variable 43
Synchronization
If two threads can both execute a method that
modifies the state of an object then the method
should be declared to be synchronized, those
allowing only one thread to execute the method at
a time
Advanced Programming
If a class has at least one synchronized method,
each instance of it has a monitor/lock
monitor is an object that can block threads and
notify them when the method is available
Example: two passengers are trying to book seats
at the same time and observe that only two seats
are available
Passenger #1 books 2 seats and simultaneously 44
Synchronization
Advanced Programming
45
Synchronization
Syntax to declare Synchronized method in Java
Acess_modifiers synchronized return_type method_name (Method_Parameters)
{
//**** critical code goes here …
} Only one thread may be inside the body of this
Advanced Programming
function
A second call will be blocked until the first call
returns or wait() is called inside
public the{ synchronized
void foo()
method synchronized (this) {
If you don’t need to protect
//critical code goes here
an entire method, you can …
synchronize on an object: }
… 46
Synchronization
Threads with out
public class Synchronization implements
Synchronization
Runnable{
int avail_tickets = 3;
static int i = 1, j = 2, k = 3;
public void bookticket (String name, int
Advanced Programming
wantedtickets){
if (wantedtickets <= avail_tickets){
[Link] (wantedtickets + " booked
to " + name);
avail_tickets = avail_tickets - wantedtickets;
}
else{
47
[Link] ("No tickets to book");
Synchronization
public void run (){ Threads with out
String name = [Link]
Synchronization
().getName (); public static void main
if ([Link] ("t1")){ (String[]args){
bookticket (name, i); Synchronization s = new
} Synchronization ();
Advanced Programming
else if ([Link] ("t2")){ Thread t1 = new Thread (s);
bookticket (name, j); Thread t2 = new Thread (s);
} Thread t3 = new Thread (s);
else{ [Link] ("t1");
bookticket (name, k); [Link] ("t2");
} [Link] ("t3");
} [Link] ();
[Link] ();
[Link] (); 48
Synchronization
Threads with
class Thread_Synchron implements Runnable{
Synchronization
int counter = 1;
public void run() {
synchronized (this) {
Advanced Programming
Thread tr = [Link]();
String th_name = [Link]();
[Link]("Thread " + th_name + " is
alloted " + counter);
counter++;
}
}
} 49
Synchronization
Threads with
public class Thread_Synch {
Synchronization
public static void main(String[] args) {
Thread_Synchron count = new Thread_Synchron();
//make the threads
Thread th1 = new Thread(count);
Advanced Programming
Thread th2 = new Thread(count);
[Link]("Thread 1");
[Link]("Thread 2");
[Link]();
[Link](); Thread Thread 1 is
} alloted 1
} Thread Thread 2 is 50
Common Issues
Race Conditions: Occur when multiple threads
access shared data concurrently.
Deadlocks: Occur when two or more threads are
Advanced Programming
blocked forever, waiting for each other.
Starvation: Occurs when a thread is unable to gain
access to resources and cannot progress.
51
Best Practices
1. Prefer Runnable over extending Thread for
better flexibility.
2. Use thread pools (ExecutorService) instead of
creating threads manually.
3. Always synchronize access to shared
Advanced Programming
resources.
4. Avoid deadlocks by acquiring locks in a
consistent order.
5. Use higher-level concurrency utilities from
the [Link] package.
52
53
THANKS
!
Questions,
Ambiguities,
Doubts, … ???