0% found this document useful (0 votes)
2 views

Advanced Java Programming Chapter 4 - Multhithreading

Chapter Four of Advanced Programming focuses on multithreading, explaining the concepts of multitasking, processes, and threads. It details the advantages and disadvantages of single-threaded versus multi-threaded programming, types of threads, and the lifecycle of threads in Java. The chapter also covers how to create and manage threads in Java, including extending the Thread class and implementing the Runnable interface.

Uploaded by

btbonsa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Advanced Java Programming Chapter 4 - Multhithreading

Chapter Four of Advanced Programming focuses on multithreading, explaining the concepts of multitasking, processes, and threads. It details the advantages and disadvantages of single-threaded versus multi-threaded programming, types of threads, and the lifecycle of threads in Java. The chapter also covers how to create and manage threads in Java, including extending the Thread class and implementing the Runnable interface.

Uploaded by

btbonsa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Advanced Programming---Chapter Four---

Multithreading
1

{ Chapter 4: Multithreading

Thursday, March 13, 2025


Overview 2

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 Multitasking is a process of executing multiple tasks simultaneously

 Is the ability to have more than one program working at what seems like
at the same time. For example, you can print while editing or sending a
fax.

 Multitasking can be achieved in two ways:

 Process-based Multitasking (Multiprocessing)

 Thread-based Multitasking (Multithreading)

 Today’s operating systems are multiprocessing (often called


multitasking)
Overview 3

 Process:

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 is an executing instance of a program loaded into memory with all the
resources needed to operate (You are familiar with processes, because each
time you run a program on your computer, you start a process. )
 Each process has a separate memory address space, i.e., each process runs
independently
 Thread:
 A thread is the unit of execution within a process.
 A thread cannot exist on its own; it must be a part of a process. A process
can have one thread or more threads.
 Each thread in the process shares memory and resources allotted at start time of
the process.
 It is similar to a process but executes within the context of a process
 In single-threaded processes, the process contains one thread.
Overview: Basic Concepts 4
Process Thread

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 Processes are heavyweight  Threads are lightweight operations
operations  Use the memory of the process they
 Each process has its own memory belong to
space---  Inter-thread communication is faster
 Inter-process communication is slow  Context switching between threads
 Context switching between of the same process is less
processes is more expensive expensive
 Threads share memory with other
 Processes don’t share memory with
threads of the same process
other processes
 A problem with one thread in a
 Not vulnerable to problems caused
process will affect other threads and
by other process as each are
the viability of the process itself
independent instances of a program
A program can have multiple A process can have multiple
process: thread:
Multi-processing Multi-threading
Overview 5

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 Computer users take it for granted that their systems can do more than one thing at a
time.

 They assume that they can continue to work in a word processor, while other
applications download files, manage the print queue, and stream audio.

 Even a single application is often expected to do more than one thing at a time.

 Example 1: streaming audio application must simultaneously read the digital audio of
the network, decompress it, manage playback, and update its display.

 Example 2: GUI-driven program may be displaying a background animation while


processing the user’s foreground interactions with the interface.

 Example 3: Web browser may need to download and display the contents of a
graphics file while rendering the rest of the associated Web page.

 Software that can do things concurrently is known as concurrent software.


Overview 6

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 The OS divides processing time not only among different applications, but also
among each thread within an application.

 Multithreaded programs extend the idea of multitasking by taking it one level


lower: individual programs will appear to do multiple tasks at the same time.

 A multi-threaded program contains two or more parts that can run


concurrently.

 Each part can handle a different task at the same time that enables optimal
use of the available resources.

 Thus, Multithreading enables multiple tasks in a program to be


executed concurrently.
Overview 7

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 Advantage of Single thread over  Advantage of multi-threaded
multiple thread programming
 Reduces overhead in the application as  Enables parallel processing of
single thread execute in the system multiple operations
 Reduces maintenance cost of the  Improved response time to user
application
 Users are not blocked because
 Disadvantage of Single thread threads are independent
 Resource wastage  Allows to utilize the idle time of
(i.e., idle CPU time or memory) the CPU
 Delayed response time.  Enables to prioritize your work
 Users may be blocked to perform activities depending on priority
Overview: Types of Thread 8

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 In General there are two types of thread

1. User Level: User managed threads

2. Kernel Level: Operating System managed threads acting on kernel, an


operating system core.

 User thread:

 Are created by the application (user) to perform some specific task.

 JVM will wait for user threads to finish their tasks

 JVM will not force the user threads to terminate.

 User threads are high priority threads, They are designed to execute important
task in an application.

 User threads are foreground threads.


Overview: Thread Life
1. New: A new thread begins its life cycle. 9
Cycle(States)
 It remains in this state until the program starts the thread.
Runnable/Ready: started to be executing its task, but not owned lock

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
2.
 Changed after start() method is called
 May changed from running state with yield() method
 if a thread has been put to sleep and the sleep time has expired, the thread is reactivated
and enters the Ready state.

3. Running: currently active to perform task or owned lock


4. Blocked: inactive state
 Waiting :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 : Thread at 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.

5. Terminated (Dead) : A runnable thread enters the terminated state when


it completes its task or otherwise terminates.
Overview: Thread Life 10
Cycle(States)

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---

A thread's state changes based on:

 Control methods such as start, sleep, yield, wait, notify

 Termination of the run method


11
All processes have at
least one thread of

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
execution, which is
usually called the
main
thread, because it is
the one that is
executed when your
program begins.
Multithreaded Programming in
Java
THE PROGRAMS WE HAVE WRITTEN UP UNTIL NOW IN THE
COURSE HAVE HAD A SINGLE PATH OF EXECUTION: THE MAIN() METHOD .
Multithreading in Java 12
 A multi-threaded program contains two or more parts that can run

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
concurrently and each part can handle a different task at the same time
making optimal use of the available resources specially when your
computer has multiple CPUs.
 How thread works?
 Each thread is given its own "context"
 The "scheduler" decides which thread executes at any given time
 The VM may use its own scheduler or may use the Operating system's scheduler for
scheduling threads
 The scheduler maintains a list of ready threads (the run queue) and a list of threads
waiting for input (the wait queue)
 Each thread has a priority.
 The scheduler schedules between the highest priority threads in the run queue
 Note: the programmer cannot make assumptions about how threads are
going to be scheduled.
 The operating system or JVM is responsible for scheduling and allocating resources to
Multithreading in Java 13

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 With Java, we can launch multiple threads from a program
concurrently.

 These threads can be executed simultaneously

 In single-processor systems, the multiple threads share CPU time, the


operating system is responsible for scheduling and allocating resources to
them.
Creating Threads In Java 14

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 When an application executes, the main method is executed by a single
thread.

 If the application requires more threads, the application must


create them.

 A thread in java can be defined in two ways

1. Extend the java.lang.Thread class

2. Implement the Runnable interface


Extending Java Thread class 15
 The Thread class contains the constructors for creating threads for tasks and the

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
methods for controlling threads.

 Thread class implements Runnable interface

 Steps to create Thread with Thread class


1. Define a class that extends Thread and implements the run method

class MyClass extends Thread{

public void run( ){..}

2. Then create an object from the class

MyClass mc = new MyClass();

3. Invoke its start method to start the thread


run() Method
16
 The body of the run() method is the path of execution for your

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
thread.
 The run() method specifies the actions that a thread is to execute and serves the

same purpose for the process running on the thread as method main() does for a full

application program.

 Like main(), run() may not be called directly. The containing

program calls the start() method (inherited from class Thread), which

then automatically calls run.

 When the thread starts running, the run() method is invoked, and

the thread becomes dead when the run() method runs to

completion.
Advanced Programming---Chapter Four---
17

Multithreading
Thursday, March 13, 2025
Example: Extending Thread
Class
Implementing the Runnable
18

interface
Three basic steps

You need to implement a run() method provided by a

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
1.

Runnable interface
class ImplClass implements Runnable{

public void run( ){..}

2. Instantiate a Thread object using the following constructor:


o Thread threadObject= new Thread(Runnable target)

• Where, target is an instance of a class that implements the Runnable


interface

3. start the thread by calling start() method, which executes a


call to run( ) method
Advanced Programming---Chapter Four---
19

Multithreading
Thursday, March 13, 2025
Example: Implementing the
Runnable interface
Extending Thread Vs. 20
Implementing Runnable Interface

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 Extending Thread class  Implementing Runnable
 The derived class itself is a  does not give developers any
thread object and it gains full control over the thread itself, as it
control over the thread life cycle. simply defines the unit of work that will

 be executed in a thread.
The derived class cannot extend
any other base classes because  the class can still extend other base
Java only allows single classes if necessary.
To summarize:
inheritance.
 If the program needs a full control over the thread life cycle, extending
the Thread class is a good choice,
 If the program needs more flexibility of extending other base classes,
implementing the Runnable interface would be preferable.
 If none of these is present, either of them is fine to use.
Thread Methods 21
Method Description
public void start() Starts the thread in a separate path of execution, then invokes the run()

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
method on this Thread object.

public void run() If this Thread object was instantiated using a separate Runnable target,
the run() method is invoked on that Runnable object.

public final void setName(String name) Changes the name of the Thread object. There is also a getName()
method for retrieving the name.

public final void setPriority(int priority) Sets the priority of this Thread object. The possible values are between
1 and 10.

public final void setDaemon(boolean A parameter of true denotes this Thread as a daemon thread.
on)
public final void join(long millisec) The current thread invokes this method on a second thread, causing the
current thread to block until the second thread terminates or the
specified number of milliseconds passes.
public void interrupt() Interrupts this thread, causing it to continue execution if it was blocked
for any reason.

public final boolean isAlive() Returns true if the thread is alive, which is any time after the thread has
been started but before it runs to completion.
Methods on currently running 22

thread
public static void yield() Causes the currently running thread to yield to any other threads of

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
the same priority that are waiting to be scheduled.
public static void sleep(long Causes the currently running thread to block for at least the
millisec) specified number of milliseconds.

public static boolean


Returns true if the current thread holds the lock on the given Object.
holdsLock(Object x)

public static Thread Returns a reference currentThread.getName(): Name of running


currentThread() to the currently thread
running thread,
which is the thread currentThread.getPriority(): Priority of running
that invokes this thread
method. currentThread.getID(): identifier of running
thread
currentThread.getState(): state of running
thread
public static void dumpStack() Prints the stack trace for the currently running thread, which is useful
when debugging a multithreaded application.
Starting Thread: start() 23

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 You must call the start method in your object to actually start a
thread.
 A new thread is only started by the start method.
 That new thread then executes the run method.
 Can we start thread twice? No, if a thread is started it can
never be started again, if you do so, an
illegalThreadStateException is thrown.
Temporarily release time for 24

other Thread: yield()

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 You can use the yield() method to temporarily release time for other
threads.

ThreadA ThreadB
 Suppose it two threads ThreadA to print number and ThreadB to print
characters are running,
 every time a number is printed, the ThreadA task is yielded and ThreadB get
running.
 So each number is followed by some characters.
Pausing a Thread: sleep() 25

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 Pausing a thread
 public static void sleep(long millis) throws InterruptedException
 pauses the execution of current thread for specified time in
milliseconds.
 The actual time thread sleeps before waking up and start
execution depends on system timers and schedulers.
 Thread sleep doesn’t lose any monitors or locks current
thread has acquired.
 For example, the code below puts the thread in sleep state
for 3 minutes:
The join() Method: Waiting for
completion of another thread 26

 The join method allows one thread to wait for the completion of another.

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 Like the wait() and notify() methods, join() is another mechanism of
inter-thread synchronization.
 If t is a Thread object whose thread is currently executing: t.join();
 causes the current thread to pause execution until t's thread terminates.

 However, as with sleep, join is dependent on the OS for timing, so you


should not assume that join will wait exactly as long as you specify.
 Like sleep, join responds to an interrupt by exiting with an
InterruptedException.
Advanced Programming---Chapter Four---
27

Multithreading
Thursday, March 13, 2025
suspend() and resume()
Suspend and resume:
Thread Priority
Every Java thread has a priority that helps the operating system determine the
28
order in which the threads are scheduled.

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
A thread’s priority determines, in part, how much CPU time a thread
receives. In general, low-priority threads receive little. High-priority threads
receive a lot.

You can reset the priority using setPriority(int priority)

The possible values of priorities are between (1 and 10).

Thread with higher priority are more important to a program.

The Thread class has the int constants MIN_PRIORITY, NORM_PRIORITY, and
MAX_PRIORITY, representing 1, 5, and 10, respectively.

Each thread is assigned a default priority of Thread.NORM_PRIORITY (constant of 5).


Thread Scheduling

29
An operating system’s thread scheduler determines which thread runs next.

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 The thread scheduler mainly uses preemptive or time slicing scheduling to
schedule the threads.
1. Preemptive scheduling: the highest priority task executes until it enters the waiting or
dead states or a higher priority task comes into existence.

2. Time slicing: a task executes for a predefined slice of time and then reenters the pool of
ready tasks.

 Starvation: Higher-priority threads can postpone the execution of


lower-priority threads.
 Solution: combination of both (Preemptive scheduling and Time slicing) in which
highest priority task executes but only for limited time slice allowing low priority
tasks to execute their task.

 There is no guarantee that which runnable thread will be chosen to run by


30

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
Reading Assignment
DAEMON THREAD IN JAVA,
THREAD POOLS,
SYNCHRONIZATION, AND
DEADLOCK AVOIDANCE
USING EXECUTOR INTERFACE
Using Executor interface 31

 Executer interface is included under

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
java.util.concurrent package
 The newFixedThreadPool(int) method
creates a fixed number of threads in a pool.
 If a thread completes executing a task, it can
be reused to execute another task.
 If a thread terminates due to a failure prior to
shutdown,
 a new thread will be created to replace it if all the threads in
the pool are not idle and there are tasks waiting for execution.

 The newCachedThreadPool() method


creates a new thread if all the threads in the
pool are not idle and there are tasks waiting
for execution.
 A thread in a cached pool will be terminated
if it has not been used for 60 seconds.
 A cached pool is efficient for many short
Using Executor interface 32
Line 3 creates a thread pool executor with three

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
threads maximum.
Line 5 creates a task new A() and adds it to the
pool. Another two runnable tasks are created and
added to the same pool in lines 6–7 similarly.
The executor creates three threads to execute three
tasks concurrently.
Suppose that we replace line 3 by:
ExecutorService executor =
Executors.newFixedThreadPool(1);
The three runnable tasks will be executed
sequentially, because there is only one thread in the
pool.
N.B: if we need to create a Suppose you replace line 3 by:
ExecutorService executor =
thread for one task, using the Executors.newCachedThreadPool();
Thread class is good choice New threads will be created for each waiting
else if we need to create task, so all the tasks will be executed concurrently.
threads for multiple tasks, it The shutdown() method in line 9 tells the
is better to use a thread pool. executor to shut down. No new tasks can be
accepted, but the existing task will continue to finish.
Thread Synchronization
33
 With multiple thread, there is may be a situation when multiple

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
threads try to access the same resource and finally they can
produce unforeseen result due to concurrency issues.
 e.g., if multiple threads try to write within a same file then they may corrupt the data
because one of the threads can override data or while one thread is opening the same
file at the same time another thread might be closing the same file.

 To deal with such situation, Synchronization is required

 Synchronization: the action of make sure that only one thread can access the
resource at a given point in time.
 Only one thread at a time may hold a lock on a monitor.

 Locking is achieved by placing the keyword synchronized in front of the method definition or
block of code that does the updating.

 To enter critical section, a thread needs to obtain the corresponding object’s lock.
Thread Synchronization 34

 To avoid race conditions (accessing a common resource in a way that

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
causes conflict),
 We need to prevent more than one thread from simultaneously entering a certain
part of the program, known as the critical section.

 A class is said to be thread-safe if an object of the class does


not cause a race condition in the presence of multiple threads.
 In java, we can achieve synchronization through 3 ways
1. Synchronizing methods

2. Synchronizing blocks

3. Static Synchronization
Example: Bank transaction
 Consider a bank offering online access to its customers to 35
perform transactions on their accounts from anywhere.

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 It is possible that an account holder has given a cheque
to some other account holder.
 If the cheque recipient happens to withdraw the money at the
same time the original account holder deposits the money, both
parties are performing simultaneous operations on the same
account.
 This situation can lead to incorrect operation on the account.
How to fix it?
 This can be avoided by adding synchronized keyword to shared
methods such as deposit and withdrawal, to assure only one
person is able to perform an operation on a shared data at a time.
 Exercise: Check the effect with and without synchronized keyword
for deposit and withdrawal methods
Using synchronized Keyword
36
 You can use the keyword synchronized to synchronize the

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
method so that only one thread can access the method at a
time.
 A synchronized method acquires a lock before it executes.
 In the case of an instance method, the lock is on the object for which the
method was invoked.

 In the case of a static method, the lock is on the class.

 If one thread invokes a synchronized instance method (respectively, static


method) on an object, the lock of that object (respectively, class) is acquired
first, then the method is executed, and finally the lock is released.

 Another thread invoking the same method of that object (respectively, class)
Synchronizing Blocks
37
 A synchronized blocks enable us to synchronize part of the code

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
in a method instead of the entire method.
 This block is referred to as a synchronized block.
 This increases concurrency.
 The general form of a synchronized statement is as follows:

 The expression expr must be an object reference.


 If the object is already locked by another thread, the thread is
blocked until the lock is released.
 When a lock is obtained on the object, the statements in the
synchronized block are executed, and then the lock is released.
Inter-thread Communication
38
 Thread synchronization be sufficient to avoid race conditions by ensuring the

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
mutual exclusion of multiple threads in the critical region, but sometimes we
also need a way for threads to cooperate.
 Making synchronized threads communicating with each other.
 It is a process in which a thread is paused in its critical section and another
thread is allowed to enter in the same critical section to be executed.
 Implemented by (wait, notify and notifyAll may only be called when the current thread

has a lock on the object):

 Wait(): calling thread give up the monitor and go to sleep until some other thread enters
the same monitor and calls notify().

 Notify(): wake up the first thread that called wait() method.

 NotifyAll(): wakes up all threads those called wait() and the one with highest priority will
Advanced Programming---Chapter Four---
39

Multithreading
Thursday, March 13, 2025
Example
Deadlock
40
 A state of deadlock occurs when threads are waiting

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
for events that will never happen.
 Consider the scenario with two threads and two objects
 Thread 1 has acquired a lock on object1, and Thread2 has
acquired a lock on object2.
 Then Thread 1 is waiting for the lock on object2
 Thread 2 is waiting for the lock on object1.
 Each thread waits for the other to release the lock it needs, and
until that happens, neither can continue to run.
Avoiding Deadlock
41
 Deadlock can be easily avoided by resource ordering.

Thursday, March 13, 2025


Multithreading
Advanced Programming---Chapter Four---
 With this technique, assign an order on all the objects whose locks
must be acquired and ensure that the locks are acquired in that order

 For the example in the above scenario


 suppose that the objects are ordered as object1 and object2.

 Using the resource ordering technique,

 Thread 2 must acquire a lock on object1 first, then on object2.

 Once Thread 1 acquires a lock on object1, Thread 2 has to wait for a lock
on object1.

 So Thread 1 will be able to acquire a lock on object2 and no deadlock will


occur
Advanced Programming---Chapter Four---
42

Multithreading
Thursday, March 13, 2025
End of Chapter 4 }

You might also like