Java Programming
Chapter 10
MULTITHREADING
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Agenda
10.1 Introduction
10.2 Threads in Java
10.3 Thread Creation
10.4 Life Cycle of a Thread
10.5 Joining a Thread
10.6 Thread Scheduler
10.7 Thread Priority
10.8 Thread Synchronization
10.9 Inter-thread Communication
10.10 Thread Control
10.11 Thread Pool
10.12 Thread Group
10.13 Daemon Thread
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
10.1 Introduction
All modern programmers need to develop applications that can perform
many tasks concurrently. Multithreading enables the developer to develop
such dynamic applications.
Before getting deeper into the concept, let us understand what actually is
a process and thread.
A process is nothing but a program in execution. If a program or a process is
subdivided into smaller tasks or jobs, each such task is called as thread.
A single process or a program may have many threads that can run
simultaneously and do different tasks at a time.
It is done to utilize the CPU time well. A process of running more than
one thread concurrently is known as multithreading.
Threads are lightweight sub-processes. If one thread triggers an
exception, it does not affect the other threads which are executing
concurrently.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Comparison of multitasking, multithreading,
multiprocessing
Multitasking Multithreading Multiprocessing
Capacity to run more A single process that It is much like
than one process contains more than one multitasking doing
concurrently in a thread (sub-processes) with more than one
single CPU running simultaneously CPU.
environment. is called as a It is a process-based
Multitasking may be Multithread. multitasking
Process-based or It is a thread-based
Thread-based multitasking
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
10.2 Threads in Java
In Java, multithreading is achieved using a Thread class and Runnable
interface.
If the program needs to create a thread, it should either extend the Thread
class or implement the Runnable interface.
Thread class in [Link] package provides many useful constructors and
methods which are used for creating and working with threads.
S. No
Constructors of a Thread Class
1. Thread()
1. Thread(String n)
1. Thread(Runnable r)
1. Thread(Runnable r, String n)
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
The important methods possessed by a Thread class.
S. No Methods Description
1. run() This method implements the behavior of a thread.
It starts the execution of a thread by invoking the run()
method. Once the thread is started, it cannot be restarted
2. start()
again. If try do so, it will throw an
illegalTheadStateException.
Stops the execution of a thread for a specified period of
sleep(long
3. time in milliseconds.(1000 milliseconds is equalent to 1
milliseconds)
second)
join(long Makes the thread wait for a specified number of
4. milliseconds) milliseconds and then start its execution.
Checks whether the thread is alive or not. If not, returns
5. isAlive()
false.
It temporarily pauses the currently executing thread to
6. yield()
allow other threads to execute.
7. suspend() Suspends the thread
8. resume() Resumes the thread which was suspended
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
9. stop() Stops the thread from its execution.
10. getPriority() Returns the current priority of a thread
setPriority(int
11. Sets the priority for a thread
priority)
12. getName() Returns the name of a thread
setName(String
13. It sets the name for a thread
name)
14. interrupt() This method is used to interrupt the thread
15. isInterrupted() Checks whether the thread has been interrupted or not.
public Thread
16 Returns the reference of currently executing thread.
currentThread()
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Main Thread
Whenever a Java program starts its execution, a default thread of that
program automatically starts execution simultaneously.
So what is the default thread? In Java, the execution of a program starts
from the class which has the main() function.
The class which has a main() function is also called as main thread or
default thread. All other threads are called as child threads.
The main thread can also be controlled using a Thread object.
To manipulate a main thread, the following method is used:
static Thread currentThread()
The currentThread() method returns the reference of a thread in which it
is invoked.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
10.3 Thread Creation
Java is a multi-thread programming language; its multithreading
capability is supported by the built-in libraries which enable the
programmer to develop applications that can support parallel processing.
In Java, a thread can be created by the following two ways, using which,
any class can become a thread.
By implementing the Runnable interface
By extending the Thread class
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Creating a thread by implementing Runnable
interface
STEP 1: As a first step, the thread should be created through
implementing a Runnable interface.
STEP 2: Define a run() method inside the thread. The run() method can
be used only after implementing the Runnable interface.
STEP 3: Place the run() method inside the class which implements a
Runnable interface.
STEP 4: Next is to instantiate a Thread class inside the main() method and
use that object to execute a thread.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Creating a thread by extending Thread class
The second way to create a thread is by extending a Thread class. The
class which extends the Thread class will become a sub class.
The inheritance of Thread class is given below:
public class Thread extends object implements Runnable
STEP 1: Create a class by extending a Thread class
STEP 2: Override the run() method of a Thread class and place it inside
the class which extends the Thread class.
STEP 3: Create an object for the thread inside the main() method.
STEP 4: Invoke the start() method through the object of the Thread class
to execute the run() method of a thread.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Thread Class vs. Runnable Interface
Thread class Runnable interface
Once the class extends a thread class to The class which implements Runnable
create a thread, it cannot extend other interface to create a thread has more
classes because Java does not support space for inheriting other classes. So, it
multiple inheritance. allows multiple inheritance
Each access has its own object. So for
It shares the same object across
each access, a separate object should
multiple accesses.
be created.
Multiple objects creation consume Sharing same object reduces the
more memory memory overhead.
Code is tightly coupled Code is loosely coupled
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Choosing a method for thread creation
If the class needs to inherit more than one class, it is better to create a
thread by implementing Runnable interface.
If the programmer wants to pass Runnable to any other thread or thread
pool, Runnable interface is a good choice
If the thread is going to use only run(), implement with the Runnable
interface. Because the Thread class not only overrides run()method and
it overrides all the methods in the Thread class.
If the programmer needs to reuse the run(), better go for Runnable
interface.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
10.4 Life Cycle of a Thread
As a sub-process, a thread also has its own life cycle stages. Every thread
should go through these life cycle stages until it is destroyed.
According to the specifications of Sun Java, there are only four states in
the life cycle of a thread in Java, namely new, runnable, non-runnable and
terminated.
So there is no running state in a thread as per the specifications of Sun
Java. The life cycle of a thread is controlled by the JVM (Java Virtual
Machine) in Java.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
10.5 Joining a Thread
A sleep() method makes a currently running thread wait for some
specified seconds in a non-runnable state, for other threads to complete
their task.
In Java, one thread can know the execution status of other threads by
using two different methods isAlive() and join().
isAlive() method join() method
It returns either true or false. It is used more frequently than
True when a thread upon which it is isAlive() method.
called still running. Unlike isAlive() method, this
False when a thread upon which it is method makes the current thread
called finished execution. wait for a particular period of time
until the specified thread finishes its
execution.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
10.6 Thread Scheduler
Scheduling a thread is one of the jobs of a JVM (Java Virtual Machine).
It is difficult to determine which thread in a runnable state will be chosen
for execution.
A preemptive scheduling or a time slice scheduling policy is primarily
used by the thread scheduler to choose threads from runnable states for
execution.
At a time only one thread in a process will be executed.
Preemptive Scheduling Policy Time slice Scheduling Policy
It chooses the thread based on round
robin scheme; a thread is allowed to
Higher priority thread will be executed first, execute only for a particular period of
until it is moved to non-runnable state or time. After that it must be moved to non-
other higher priority thread comes into runnable state. The thread scheduler then
existence. decides which next thread is moved to
runnable state based on some factors.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
10.7 Thread Priority
The operating system assigns priority for a process to be allocated to the
processor.
The process which has the highest priority will be scheduled first to the
processor by the process scheduler.
Like a process, a thread can also be assigned priority using setPriority()
method.
The Thread class provides three constants such as MAX_PRIORITY,
MIN_PRIORITY and NORM_PRIORITY to specify the priorities for the
threads.
Normally, priorities are represented from 1 to 10. MIN_PRIORITY has a
default value of 1 and MAX_PRIORITY has 10, NORM_PRIORITY has
a thread priority of 5.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
10.8 Thread Synchronization
There may be a situation where more than one thread tries to write to the
same document simultaneously. If so, the data in that document will be
overwritten.
The reason behind this chaos is that there is no control over the shared
resource by all the threads.
The process of controlling the access of shared resources by more than
one thread is called synchronization.
Synchronization helps to ensure that the resource is accessed by only one
thread at a time and preserves consistency of the resources during
multiple accesses.
A semaphore or monitor is a key to synchronization. The monitor is an
object that is used as a mutually exclusive lock or mutex.
Only one thread at a time can hold a monitor. All other threads attempting
a shared resource are suspended until the resource is released.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Java implements a synchronization using the following statement:
synchronized(object)
{
// block of code
}
The object is the one which is going to be synchronized.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
10.9 Inter-thread Communication
Inter-thread communication is a way to allow synchronized threads to
exchange information or interact with each other and this is the only way
to handle the producer-consumer problem in thread communication.
When the threads are interacting with each other without using the
methods defined by an object class, the resulting data will be scrambled.
The following methods are used to implement thread communication in
Java.
wait()
notify()
notifyAll()
The above three methods should be called only within the synchronized
context.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
wait()
Makes the current thread to release the monitor and waits until either of
the following things happens:
Another thread calls the notify() or notifyAll() method.
The specified time is intervened or is over.
The current thread which owns the monitor should be called from the
synchronized method; otherwise, it will throw an exception.
Sl. No Method Description
1. public final void wait() waits until object is notified.
2. Public final void wait(long timeout) waits for the specified amount of
time.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
notify()
It notifies a single thread that was put in a waiting state by invoking a
wait() method.
public final void notify()
notifyAll()
Wakes up all the threads that are waiting in the monitor. The thread which
has the highest priority will run first.
public final void notifyAll()
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Difference between wait() and sleep() methods
wait() method sleep() method
It releases the lock It does not release the lock.
Contained in the Object class Contained in the Thread class
It is a non-static method It is a static method
Waked by notify() or notifyAll() After the sleep time is completed.
methods
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
10.10 Thread Control
Having control over the execution of a thread is sometimes useful.
When the operation of a thread is not required, it can be stopped or
suspended instead of letting the thread to go on to finish its task
completely.
Java provides an efficient way to control the execution of a thread using
the following methods of a Thread class.
public void suspend()
public void resume()
public void stop()
suspend()
The suspend() method is used to halt the currently running thread until it is
resumed using the resume()
method. Unlike sleep(), the suspend() method can’t just resume operation after
a time period. It expects a resume() method to be called.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
resume()
This method resumes the thread which was suspended using the suspend() method.
It lets the thread start its operations from where it left off before the suspend()
method was invoked.
stop()
A thread is alive during the suspend and resume operations.
But when the thread object invokes the stop() method, it is stopped once and for all.
Once the stop() method is called, it is not possible to get back the thread during run
time.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
10.11 Thread Pool
A thread pool represents a group of threads just like workers in a factory.
In a thread pool, a fixed number of threads are created. If a worker in a
factory completes a task, another task can be allocated. Likewise, if a
thread completes its allocated task, another task can be allocated. In this
way, a thread may be used several times.
Each thread in a thread pool has the following life cycle:
1. Listen for a new task to be allocated.
2. Complete the task.
3. Return to the thread pool for getting the next task.
In Java, a thread can be created by two ways: the first one is through the
Thread class and the second through the Runnable interface. Once a
thread is created and terminated, it cannot be reused again by using the
Thread class.
Using a Runnable interface, a pool of threads is created and used again
and again, instead of creating individual threads many times.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
It groups the various threads in one convenient group.
Through an object of a Thread Group, all the threads belonging to that
group can be manipulated.
In a Thread Group, threads can be added or removed at any time. In Java,
a Thread Group can be created by using [Link] class.
Before placing more than one thread in a Thread Group, A Thread Group
should be created first.
The following code snippet demonstrates how the thread group is created
ThreadGroup tg=new ThreadGroup(“Arithmetic”);
In the above code snippet, Arithmetic is a name of a ThreadGroup and tg
is an object of a ThreadGroup.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Constructors in a ThreadGroup
S. No. Constructor Description
1. ThreadGroup(String n) Generates a thread group with
specified name. Parameter n used to
specify the name for a thread group.
2. ThreadGroup(ThreadGroup Generates a thread group with
p, String n) specified parent group and name.
Methods in a ThreadGroup
S. No. Method Description
returns a number of threads executing in current
1. activeCount()
Thread Group.
returns a number of active group in this thread
2. activeGroupCount()
group.
3. destroy() destroys thread group
4. getName() returns the name of the Thread Group.
5. ThreadGroup getParent() returns the parent.
6. interrupt() interrupts all threads in this Thread group.
7. list() prints information about thread group.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
10.13 Daemon Thread
Java daemon thread is a service provider thread and it mostly runs in the
background.
It serves the user threads. When user threads are no longer running, a
daemon thread is destroyed by the JVM automatically, as the daemon
thread is executed only for providing service for the user threads.
These types of threads are low priority threads. The [Link]
class provides methods to handle daemon threads.
S. No Method Description
public void setDaemon(boolean Sets the current as a
1. status) Daemon thread
Checks whether the given
public boolean isDaemon() thread is daemon thread or
2.
not
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Summary
A process is nothing but a program in execution. If a program or a process is
subdivided into smaller task or job, each such task is called as thread.
A process of running more than one threads concurrently is known as
Multithreading.
A thread can be created by either of the following two ways: Through Runnable
interface or Through extending the Thread class
In Java, one thread can know the execution status of other threads by using two
different methods isAlive() and join().
A thread can be assigned priority using setPriority() method. The Thread
class provides three constants such as MAX_PRIORITY, MIN_PRIORITY and
NORM_PRIORITY to specify the priorities for the threads.
Thread pool represents a group of threads just like workers in a factory.
ThreadGroup groups the various threads in one convenient group.
Java daemon thread is a service provider thread and it mostly runs in the
background. It serves the user threads.
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi