Threads in Java
Threads in Java
A thread in Java is the direction or path that is taken while a program is being executed. Generally, all
the programs have at least one thread, known as the main thread, that is provided by the JVM or Java
Virtual Machine at the starting of the program’s execution. At this point, when the main thread is
provided, the main() method is invoked by the main thread.
A thread is critical in the program because it enables multiple operations to take place within a single
method. Each thread in the program often has its own program counter, stack, and local variable.
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. Java Multithreading is mostly used in games, animation, etc.
Application of Thread
When we execute an application: - The JVM creates a Thread object whose task is defined by the
main() method - It starts the thread - The thread executes the statements of the program one by one
until the method returns and the thread dies
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
o Each process has an address in memory. In other words, each process allocates a separate
memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
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.
There are different states Thread transfers into during its lifetime, let us know about those states
in the following lines: in its lifetime, a thread undergoes the following states, namely:
1. New State
2. Active State
3. Waiting/Blocked State
4. Timed Waiting State
5. Terminated State
1) Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread
class extends Object class and implements Runnable interface.
2) 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().
IMPLEMENTATION