CHAPTER 7
MULTITHREADING
By: Prof. Aayushi Shah
BCA DDU
JAVA PROGRAMMING
MULTITHREADING
Multithreading in Java is a process of executing multiple
threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of
processing. Multiprocessing and multithreading, both are used
to achieve multitasking.
However, we use multithreading than multiprocessing because
threads use a shared memory area. They don't allocate separate
memory area so saves memory, and context-switching between
the threads takes less time than process.
Real-life examples: Watching a video while downloading files.
A game running background music, user controls, and rendering
graphics simultaneously.
■2
MULTITHREADING
Multitasking
Multitasking is a process of executing multiple tasks
simultaneously. We use multitasking to utilize the
CPU(Responsible for all task). Multitasking can be
achieved in two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)
■3
MULTITHREADING
1) Process-based Multitasking (Multiprocessing)
Each process has an address in memory. In other words,
each process allocates a separate memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some
time for saving and loading registers, memory maps,
updating lists, etc.
■4
MULTITHREADING
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
■5
MULTITHREADING
What is Thread in java?
A thread is a lightweight subprocess, the smallest unit of
processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one
thread, it doesn't affect other threads. It uses a shared
memory area.
■6
MULTITHREADING
■7
CONT.
• The large circles (Process 1, Process 2, and Process 3)
represent independent processes.
• The smaller circles (t1, t2, t3) inside each process represent
threads within that process.
• In process 1, There are three threads (t1,t2,t3) working
together.
• These threads can communicate and share data because they
belong to the same process.
• In Process 2, there are two threads (t1, t2).
• In Process 3, there is only one thread (t1).
• This process does not utilize multithreading but operates as
a single-threaded process.
MULTITHREADING
Java Thread class
Java provides Thread class to achieve thread programming.
Thread class provides constructors and methods to create
and perform operations on a thread.
■9
MULTITHREADING
Java Thread Methods
■1
0
MULTITHREADING
■1
0
MULTITHREADING
Life cycle of a Thread (Thread States)
In Java, a thread always exists in any one of the following
states. These states are:
New
Active
Blocked / Waiting
Timed Waiting
Terminated
■1
1
MULTITHREADING
■1
2
MULTITHREADING
New: Whenever a new thread is created, it is always in the
new state.
Active: When a thread invokes the start() method, it moves
from the new state to the active state. The active state
contains two states within it: one is runnable, and the other
is running.
Runnable: A thread, that is ready to run is then moved to
the runnable state.
Running: When the thread gets the CPU, it moves from the
runnable to the running state. Generally, the most common
change in the state of a thread is from runnable to running
and again back to runnable.
■1
3
MULTITHREADING
Blocked or Waiting: Whenever a thread is inactive for a
span of time (not permanently) then, either the thread is in
the blocked state or is in the waiting state.
Timed Waiting: Sometimes, waiting for leads to starvation.
For example, a thread (its name is A) has entered the critical
section of a code and is not willing to leave that critical
section. In such a scenario, another thread (its name is B)
has to wait forever, which leads to starvation.
Terminated: When a thread has finished its job, then it
exists or terminates normally.
■1
4
MULTITHREADING
How to create a thread
There are two ways to create a thread:
By extending Thread class
By implementing Runnable interface
■1
5
MULTITHREADING
Thread class:
Thread class provide constructors and methods to create
and perform operations on a thread.
Commonly used methods of Thread class:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM
calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently
executing thread to sleep (temporarily cease execution) for
■1
the specified number of milliseconds. 6
MULTITHREADING
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die
for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of
the thread.
public String getName(): returns the name of the thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the
thread.
■1
public boolean isAlive(): tests if the thread is alive. 7
MULTITHREADING
Runnable interface:
The Runnable interface should be implemented by any
class whose instances are intended to be executed by a
thread. Runnable interface have only one method named
run().
public void run(): is used to perform action for a thread.
■1
8
MULTITHREADING
Starting a thread:
The start() method of Thread class is used to start a newly
created thread. It performs the following tasks:
A new thread starts.
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run()
method will run.
■1
9
MULTITHREADING
■2
0
MULTITHREADING
■2
1
MULTITHREADING
■2
3
MULTITHREADING
Thread.sleep()
The method sleep() is being used to halt the working of a
thread for a given amount of time.
The time up to which the thread remains in the sleeping state is
known as the sleeping time of the thread.
After the sleeping time is over, the thread starts its execution
from where it has left.
The sleep() Method Syntax:
public static void sleep(long mls) throws InterruptedException
■2
4
MULTITHREADING
■2
5
MULTITHREADING
join() method
The join() method in Java is provided by the java.lang.Thread
class that permits one thread to wait until the other thread to
finish its execution.
Suppose th be the object the class Thread whose thread is
doing its execution currently, then the th.join(); statement
ensures that th is finished before the program does the
execution of the next statement.
■2
6
MULTITHREADING
■2
7
MULTITHREADING
■2
8
MULTITHREADING
Naming Thread
The Thread class provides methods to change and get the name
of a thread. By default, each thread has a name, i.e. thread-0,
thread-1 and so on. By we can change the name of the thread
by using the setName() method. The syntax of setName() and
getName() methods are given below:
public String getName(): is used to return the name of a
thread.
public void setName(String name): is used to change the
name of a thread. Program: TestMultiNaming1
■2
9
MULTITHREADING
Thread Priority
Each thread has a priority. Priorities are represented by a
number between 1 and 10. In most cases, the thread scheduler
schedules the threads according to their priority (known as
preemptive scheduling).
■3
1
MULTITHREADING
Setter & Getter Method of Thread Priority
public final int getPriority(): The java.lang.Thread.getPriority()
method returns the priority of the given thread.
public final void setPriority(int newPriority): The
java.lang.Thread.setPriority() method updates or assign the
priority of the thread to newPriority.
■3
2
MULTITHREADING
■3
3
MULTITHREADING
■3
4
THREAD SYNCHRONIZATION
When two or more threads need access to a shared
resource, they need some way to ensure that the resource
will be used by only one thread at a time
The process by which this synchronization is achieved is
called thread synchronization
“The synchronized keyword in Java creates a block of
code referred to as a critical section. Every Java object
with a critical section of code gets a lock associated
with the object. To enter a critical section, a thread
needs to obtain the corresponding object's lock”
■3
5
CONT..
Threads are synchronized in Java through the use of a
monitor. Think of a monitor as an object that enables a
thread to access a resource
Only one thread can use a monitor at any one time period.
Programmers say that the thread owns the monitor for that
period of time. The monitor is also called a semaphore
A thread can own a monitor only if no other thread owns
the monitor
If the monitor is available, a thread can own the monitor
and have exclusive access to the resource associated with
the monitor
■3
6
CONT..
If the monitor is not available, the thread is suspended
until the monitor becomes available. Programmers say
that the thread is waiting for the monitor
You have two ways in which you can synchronize threads:
• You can use the synchronized method or
• The synchronized statement.
■3
7
SYNCHRONIZED STATEMENT
This is the general form of the synchronized statement:
• synchronized(object) { // statements to be synchronized}
Here, object is a reference to the object being
synchronized
A synchronized block ensures that a call to a method that
is a member of object occurs only after the current thread
has successfully entered object's monitor
Calls to the methods contained in the synchronized block
happen only after the thread enters the monitor of the
object
■3
8
CONT..
Synchronizing a method is the best way to restrict the use
of a method one thread at a time
However, there will be occasions when you won’t be able
to synchronize a method, such as when you use a class
that is provided to you by a third party
Although you can call methods within a synchronized
block, the method declaration must be made outside a
synchronized block
■3
9
CONT..
■4
0
CONT..
■4
1
CONT..
■4
2
JAVA SYNCHRONIZED METHOD
■4
3
JAVA SYNCHRONIZED METHOD
■4
4
JAVA SYNCHRONIZED METHOD
■4
5
JAVA SYNCHRONIZED METHOD
■4
6
Interthread Communication
• Inter-thread communication or Co-operation is all about
allowing synchronized threads to communicate with each
other.
• Cooperation (Inter-thread communication) is a mechanism in
which a thread is paused running in its critical
section(monitor) and another thread is allowed to enter (or
lock) in the same critical section to be executed.
• Simple Definition
Inter-thread communication allows threads to communicate with
each other by waiting, notifying, or signaling when certain
conditions are met, typically in a shared resource environment.
• It is implemented by following methods of Object class:
• wait( ) tells the calling thread to give up the monitor and go
to sleep until some other thread enters the same monitor and
calls notify( ).
• notify( ) wakes up the first thread that called wait( ) on the
same object.
• notifyAll( ) wakes up all the threads that called wait( ) on
the same object. The highest priority thread will run first.
These methods are declared within Object, as shown here:
1. final void wait( ) throws InterruptedException
2. final void notify( )
3. final void notifyAll( )
Program: InterThreadCommunication.java
Explain:
Producer Thread: The Producer generates data and makes it
available for the consumer. If data is already available,it waits
using wait.
Consumer Thread: The Consumer waits for data to be
available using wait() and consumes it when its available.
Inter Thread Communication: When the Producer produces
data, it calls notify() to wakeup the consumer, and when the
consumer consumes data it calls notify() to wakeup the
producer to produce more.