AMiT
Program:
Computer
Science
G3 – CS
Java Programming
Instructor:
Addisu M. (Asst.
Prof)
2
Ch ou
Multithreading
rF
ap r
te
Outline
Jan 9, 2026
Threads vs. process
Thread States
Multiple threads
Java Programming
Thread Priorities and Scheduling
Synchronization
3
Introduction
Jan 9, 2026
Human body performs variety of operations in
parallel
Computers also too, can perform operations
concurrently
Java is a multithreaded programming language
Java Programming
possible to develop multithreaded program using
Java
Only computers that have multiple processors
can truly execute multiple instructions
concurrently 4
Introduction
Jan 9, 2026
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
resources required by the program Abstract Machine Environment
Java Programming
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
Jan 9, 2026
Process & Thread - two basic units of program
execution
Thread: lightweight sub-process, smallest unit of
processing
requires less resources to create and exists in
the process
independent - if there occurs exception in one
Java Programming
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
Jan 9, 2026
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:
process begins execution at a well-known point -
main
Java Programming
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
Jan 9, 2026
Process-based Multitasking
(Multiprocessing)
Each process has an address in memory
In other words, each process allocates a separate
memory area
process is heavyweight
Java Programming
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 8
Process vs Thread
Jan 9, 2026
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
has its own address space uses the process’s address space
Java Programming
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
Jan 9, 2026
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
E.g., program has 3 threads, one and two (ThreadA &
ThreadB) other
Java Programming
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
Jan 9, 2026
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
other threads during the execution
Java Programming
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
Jan 9, 2026
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
Multiprocessing and multithreading, both are used to
achieve multitasking
Java Programming
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
Jan 9, 2026
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
the code is written
Java Programming
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
Jan 9, 2026
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
does not affect other threads during the execution
Java Programming
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
Jan 9, 2026
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
thread is less expensive than between processes
Java Programming
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
Jan 9, 2026
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
tasks
Hence, a processor will create two separate threads to
Java Programming
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
Jan 9, 2026
goes through various stages in its life cycle,
includes:
Newborn state
Runnable state
Running state
Blocked state
Java Programming
Dead state
17
Life Cycle of Thread
Jan 9, 2026
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
thread
At this state, we can do only one of the following:
Java Programming
Schedule it for running
Thread using
newThread start()
= new method
Thread(this,
Run
Kill it using“threadName”)
stop() method Dea
nabl
Syntax: Ne d
start
e stop
wb
oar
n 18
Life Cycle of Thread
Jan 9, 2026
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
execution
depends on the scheduler, whether to run the thread
Java Programming
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
Jan 9, 2026
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
access a synchronized resource
achieved when we invoked suspend() or wait()
Java Programming
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
Jan 9, 2026
Main thread – most
important part of any
application
Executed whenever a
Java program starts
Every program must
contain it for its execution
Java Programming
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
Jan 9, 2026
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();
Thread thread = new Thread(worker);
[Link]();
Java Programming
}
@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
Jan 9, 2026
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
running in background like memory management,
system management, signal processing etc
Java Programming
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
Jan 9, 2026
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)
Thread class provides constructors and methods
Java Programming
to create and perform operations on a thread
In the most general sense, you can create a thread
by instantiating an object of type Thread
Commonly used Thread()
Thread(Strin
Constructors of Thread Thread(Runna 24
g name)
Thread Class
Jan 9, 2026
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
calling run() method
Java Programming
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
Jan 9, 2026
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
• When you call start(), it internally calls
Java Programming
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
Jan 9, 2026
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();
[Link](); // create a new thread and call the
run() method
// [Link](); //just call the run() method in the
Java Programming
current thread
}
}
Two ways to create java thread
By extending thread class
By implementing Runnable 27
Create Thread
Jan 9, 2026
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
class Multi extends Thread {
run() method
public void run() {//to run thread
Java Programming
[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
Jan 9, 2026
Extending Thread class
public class MyFirstThread extends Thread {
@Override
public void run() {
[Link]("I'm Thread! My name is "
+ getName());
}
Java 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
Jan 9, 2026
Extending Thread class
I'm Thread! My name is Thread-0
Outpu I'm Thread! My name is Thread-2
t: I'm Thread! My name is Thread-4
I'm Thread! My name is Thread-1
I'm Thread! My name is Thread-3
Let's create 5 threads (MyFirstThread objects, which inherit
Java Programming
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
Jan 9, 2026
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
thread class, but we can create thread with
Java Programming
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
Jan 9, 2026
Implementing Runnable Interface
class Multi3 implements Runnable {
public void run() { Example #1
[Link](“First Thread is
running”);
}
public static void main(String args[]){
Multi3 m1 = new Multi3(); // object initiated
Java Programming
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
Jan 9, 2026
Implementing Runnable Interface
class Thread_Runnable implements Runnable {
public void run() { Example #2
for(int i=0; i < 5; i++){
[Link](“Child Thread : ” + i);
try{
[Link](50);
Java Programming
}
catch(InterruptedException ie){
[Link]("Child
thread interrupted! " + ie);
}
} 33
Create Thread
Jan 9, 2026
Implementing Runnable Interface
public static void main(String args[])
{ Output:
Thread_Runnable m = newMain thread: 10
Thread_Runnable(); Child
try{ thread: 0
for(int i = 10; i < 15; i++) Child
Java Programming
{ thread: 1
Main thread: 11
[Link]("Main thread: " + i);
[Link](1000);// Child
1000 ms = 1 sec thread: 2
} Child
} Exam thread: 3 Main
catch(InterruptedException
ple e){ thread: 12 34
Thread Class vs Runnable
Interface
Jan 9, 2026
Thread Class
Each Thread creates its unique object
More memory consumption
Java Programming
A class extending Thread class can’t extend
any other class
Thread class is extended only if there is a
need of overriding other methods of it 35
Thread Priorities
Jan 9, 2026
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
to decide when each thread should be allowed to run
In practice, the amount of CPU time that a thread
Java Programming
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
Jan 9, 2026
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
minimum priority 10 is maximum priority.
Thread class defines few priority constants:
Java Programming
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
In any Thread the default priority is
NORM_PRIORITY
getPriority() 37
Thread Priorities
Jan 9, 2026
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();
test t2 = new test();
[Link](2);
Java Programming
[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
Jan 9, 2026
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
access of shared resources by the multiple
Java Programming
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
Jan 9, 2026
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
Java Programming
Synchronization prevents such type of data 40
Synchronization
Jan 9, 2026
Why do we need Synchronization?
Synchronization allows a programmer to perform
concurrent programming and prevents data
corruption int a =
Example: 5;
int b =
Suppose that two threads exist 4;
Thread 1 performs c = a + b whileint c =
Java Programming
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
Jan 9, 2026
Why do we need Synchronization?
Java Programming
42
Synchronization
Jan 9, 2026
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:
result is unpredictable
Java Programming
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
Jan 9, 2026
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
If a class has at least one synchronized method,
each instance of it has a monitor/lock
Java Programming
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
Java Programming Jan 9, 2026
45
Synchronization
Jan 9, 2026
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
function
A second call will be blocked until the first call
Java Programming
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
Jan 9, 2026
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
wantedtickets){
Java Programming
if (wantedtickets <= avail_tickets){
[Link] (wantedtickets + " booked
to " + name);
avail_tickets = avail_tickets - wantedtickets;
}
else{
47
[Link] ("No tickets to book");
Synchronization
Jan 9, 2026
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 ();
else if ([Link] ("t2")){ Thread t1 = new Thread (s);
bookticket (name, j); Thread t2 = new Thread (s);
Java Programming
} Thread t3 = new Thread (s);
else{ [Link] ("t1");
bookticket (name, k); [Link] ("t2");
} [Link] ("t3");
} [Link] ();
[Link] ();
[Link] (); 48
Synchronization
Jan 9, 2026
Threads with
class Thread_Synchron implements Runnable{
Synchronization
int counter = 1;
public void run() {
synchronized (this) {
Thread tr = [Link]();
String th_name = [Link]();
Java Programming
[Link]("Thread " + th_name + " is
alloted " + counter);
counter++;
}
}
} 49
Synchronization
Jan 9, 2026
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);
Thread th2 = new Thread(count);
Java Programming
[Link]("Thread 1");
[Link]("Thread 2");
[Link]();
[Link](); Thread Thread 1 is
} alloted 1
} Thread Thread 2 is 50
51
THANKS
!
Questions,
Ambiguities,
Doubts, … ???