In this blog
we will understand how multi-threading works in JAVA and why is it so Important
to understand?
What is a Thread in Programming?
A thread is an autonomous unit of execution (or application
that is being executed). The phrase "multithreading" refers to the
execution of several threads in a process at the same time. Consider it the
application's equivalent of multitasking.
What Is Multithreading?
Multithreading
is a programme execution mechanism that allows several threads to be formed
within a process, each of which can execute independently while sharing process
resources. As a result, Concurrency is another name for it in Java. Threads can
execute in full parallel if they are spread to their own CPU core, depending on
the hardware.
In
Java, multitasking is achieved by multithreading and multiprocessing, however
we prefer multithreading to multiprocessing. This is because the threads share
a memory space, which saves memory and makes content swapping between the
threads a little faster than the process.
What is multithreading used for?
The main objective of adding threads to
an application is to boost its performance. Performance can be measured in a
variety of ways:
- A web server will utilize multiple threads to simultaneous
process requests for data at the same time.
- An image analysis algorithm will spawn
multiple threads at a time and segment an image into quadrants to apply
filtering to the image.
- A ray-tracing application will launch multiple
threads to compute the visual effects while the main GUI thread draws the
final results.
Multithreading
also reduces the amount of computing resources used and makes them more
efficient. Requests from one thread do not block requests from other threads,
which improves application responsiveness.
Because the
threads are independent, the user can perform multiple tasks at the same time
without being slowed down, and if one thread throws an exception, it does not
affect the other threads.
Multithreading also
consumes fewer resources than operating numerous processes at the same time.
Establishing and managing processes requires far more overhead, time, and
management than creating and managing threads.
Difference between Process and Thread
| S.No. | PROCESS | THREAD |
| 1. | Heavy weight/resource intensive | Light weight, takes lesser resources |
| 2. | Requires interaction with OS during switching | Doesn’t requires interaction with OS during switching |
| 3. | Each process has its own memory and file resources but execute the same code | Each thread shares open files and child processes |
| 4. | If one process gets blocked all the others also stop executing | If one thread is blocked, other threads in the task don’t stop executing |
| 5. | Multiple processes use more resources without threads | Multiple processes use less resources with threads |
| 6. | Each process operates independently | A thread can read or write another thread’s data |
Life cycle of a Thread
In its life cycle, a thread must go through five states.
JVM (Java Virtual Machine) is in charge of this life cycle. These are the
states:
1.
New
A new thread begins its life
cycle in this condition. A born thread is another name for this. If you create
an instance of the Thread class before calling the start() method, the thread
is in a new state.
2.
Runnable
After a newly born thread is
initiated, it becomes runnable. A thread would be executing its task in this
state.
3.
Running
The thread would then be in a
running state when the thread scheduler selects it.
4.
Non-Runnable (Blocked)
In this state, the thread is
still alive, but it is currently ineligible to run.
5.
Terminated
A thread can be terminated for
a variety of reasons:
- Its run() method exists normally, indicating that
the thread's code has completed the programme.
- or it can be terminated due to unusual errors such
as a segmentation fault or an unhandled exception.
A thread that has been
terminated does not consume any CPU cycles.
Advantages of Multithreading
1. Creating threads is more cost-effective and
time-consuming.
2. It allows threads to share resources like as data, memory, and files. Several threads can so share the same address space.
3. It improves the program's responsiveness to the
user by allowing it to continue running regardless of the situation.
4. It improves multi-processor machine performance by
increasing parallelism on multiple CPU machines.
5. It makes better use of CPU resources.
Drawbacks of Multithreading
·
While investigating data
access difficulties, if you don't use the locking mechanisms effectively,
problems such as data inconsistency and dead-lock may arise.
·
When multiple threads
attempt to access the same data, thread starvation may occur. Another issue
that can cause problems for the user is resource contention.
·
When threads display
data in an uncoordinated manner, display difficulties can occur.
Thread Creation
While
multithreading in Java, you can create a thread using two ways:
1.
By extending Thread class
2.
By implementing the Runnable interface
What is Thread Class?
The Thread class
includes methods and constructors for creating and operating on threads. Thread
is a subclass of Object that implements the Runnable interface.
In a Thread
class, various constructors are used, however the most typically used constructors
are:
·
Thread()
·
Thread(String name)
·
Thread(Runnable r)
·
Thread(Runnable r,String name)
Also, as previously mentioned, multiple thread
mechanisms are used for different purposes and tasks.
The Thread class contains these constructors and
methods to conduct various thread actions.
What is a
Runnable Interface?
It is implemented
a Runnable Interface, whose instances are designed to be executed by a thread.
It only has one method called run ().
public
void run() – This is used to perform an action for a
thread.
Starting a Thread
The start()
method is used in Java multithreading to start a newly generated thread.
- A new thread starts(with a new call stack).
- The thread moves from the New state to the Runnable
state.
- When the thread gets a chance to execute, its target run() method will run.
Thread Scheduler
The thread scheduler controls the thread pool. When the start() method
is used to start threads in a programme, each thread is stored in the thread
scheduler.
There is no guarantee as to which thread will be given priority in the
CPU. The thread with the highest priority will be handled first.
For the execution of a programme, the JVM has several threads:
·
Main: main is a method but actually, it is a thread for JVM from where
the execution starts.
·
Garbage Collector(gc()): gc() is a thread that checks after each thread
for a garbage value.
·
Timer thread: timer threads maintain the time of each thread like
wait(), sleep(), etc
Synchronization
- Multithreading allows applications to behave asynchronously. When one thread is writing data, another thread may be reading it at the same moment. This could lead to inconsistency.
- When two
or more threads require access to a shared resource, there should be a
mechanism in place to ensure that the resource is only accessed by one
thread at a time. Synchronization is the process of achieving this.
- Java has
a synchronous method for implementing synchronous behaviour. No other
thread can call another synchronised method on the same object while a
thread is within a synchronised method. The remaining threads must then
wait for the first thread to exit the synchronised block.
- We can't add the
synchronization to the necessary methods when we wish to synchronise access to
objects of a class that wasn't meant for multithreaded access and the code of
the method that has to be accessed synchronously isn't available. In Java, we
have a solution for this: insert the calls to the methods specified by this class
(that need to be synchronised) inside a synchronised block in the following
manner.
So,
this was the basic understanding of Multithreading in Java. This brings us to
an end of this blog. Hope this helped you understand Multithreading in Java
better and gain more insights into it.
Summary
Within a process, multithreading refers to the execution of numerous tasks. User-level threads and kernel-level threads are the two categories. It is cost-effective, responsive, scalable, efficient, and resource-sharing friendly. There are three types of multithreading models: many to many, many to one, and one to one.
References:
- https://www.mygreatlearning.com/blog/multithreading-in-java/
- https://totalview.io/blog/multithreading-multithreaded-applications
- https://intellipaat.com/blog/tutorial/java-tutorial/multithreading-in-java/
- Shruti Pattewar
- Kuhu Mukhopadhyay
- Tanmay Mutalik
- Aishwarya Patil
- Rehanuddin Qazi
Great information!
ReplyDeleteNice Info..!
ReplyDeleteVery Informative!!
ReplyDeleteNeatly arranged!! keep going
ReplyDeleteGood one!
ReplyDeleteNice workπ
ReplyDeleteInformative !!ππ
ReplyDeleteUseful one!!!π
ReplyDelete