Threads in Java
Threads in Java
Program: An executable file containing a set of instructions and passively stored on disk.
When a program is loaded into the memory and becomes active, the program becomes a
process.
Process: It is a program is in execution. When a process starts, requires some essential
resources such as registers, program counter, and stack, it is also assigned memory and
resources.
One program can have multiple processes. For example, the Chrome browser creates a
different process for every single tab.
• Thread: It is the smallest unit of execution within a process. It is a path followed during
a program’s execution.
• Threads are lightweight subprocesses, representing the smallest unit of execution with
separate paths.
• A process can have one or more threads. For example, in the Microsoft Word app, a
thread might be responsible for spelling checking and the other thread for inserting text
into the doc.
• Main advantage of multiple threads is efficiency (allowing multiple things at the same
time). Additionally, multithreading ensures quick response, as other threads can
continue execution even if one gets stuck, keeping the application responsive.
Threads in Java
• Multithreading in operating systems is similar to a person with
multiple hands.
• In this comparison, think a Process as a Person: A process
represents an individual person and Threads as Hands: Threads
are analogous to the person's hands.
• Think of it like a person with multiple hands working together
simultaneously to perform different parts of the same job to
complete it faster. For ex, to cook a dish, a person uses both
hands for performing different tasks—such as stirring a pot with
one hand while chopping vegetables with the other. The above
example
• A effectively
multithreaded illustrating
process how a multiple
can execute task canthreads
be performed by
concurrently, each handling a
utilizing different
separate part of a"hands"
job at the(threads) to work
same time. on separate
Example: parts ofeach
Downloading a part of a webpage
job at the same
simultaneously usingtime, maximizing
separate threads,efficiency
effectivelywithin a single
speeding up the overall download
process. Downloading a webpage using multithreading—where one thread can focus on
downloading plain text, another can download all images simultaneously, while third
thread downloads ads, if any.
This parallelism enhances efficiency and responsiveness. However, just as a
person must coordinate their hands to avoid conflicts, multithreaded processes
require careful synchronization to manage shared resources and prevent issues
like race conditions. In both scenarios, the "person" (process) maintains overall
control and coordination, ensuring that all “hands" (threads) work together
harmoniously to achieve the desired outcomes. Each “hand” is called a thread,
and they help make programs run more efficiently.