Multithreading in java is a process of executing multiple threads simultaneously. Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread.
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing because threads share a common memory area. They don’t allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways:
- Process-based Multitasking(Multiprocessing)
- Thread-based Multitasking(Multithreading)
Advantages of Java Multithreading
- It doesn’t block the user because threads are independent and you can perform multiple operations at same time.
- You can perform many operations together so it saves time.
- Threads are independent so it doesn’t affect other threads if exception occur in a single thread.
What is Thread in java?
A thread is a lightweight sub process, a smallest unit of processing.
As shown in the above figure, thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads.
Life cycle of a Thread (Thread States)
A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
- Non-Runnable (Blocked/Waiting)
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked/Wait)
This is the state when the thread is still alive, but is currently not eligible to run.
A thread is in terminated or dead state when its run() method exits.