Introduction Of Multithreading In Java
What is thread in Java?
A thread is a lightweight small part of a process or a smallest unit of processing, which can run concurrently with the other threads of the same process.
Threads are independent because they all have a separate path of execution due to which if an exception occurs in one thread, it doesn’t affect the execution of another threads and all the threads of a process shares the common memory area. The process of executing multiple threads concurrently is called as a multithreading.
Let’s understand with the figure, given below.
In the figure, given above, a thread is executed inside the process and a context-switching between the threads. Here are the multiple processes in the OS and single process can have multiple threads but only one thread is executed at a time.
Multithreading is a procedure of executing the multiple threads at the same time.
Multiprocessing and multithreading are used to achieve the multitasking in Java.
We use multithreading because the threads share a common memory area and they don't allocate separate memory area, thereby saving memory and context-switching between the threads takes less time than the process. Multithreading is mainly used in the games, animation etc.
Advantages of Multithreading
- In multithreading, the threads are independent due to which we can perform multiple operations at the same time.
- We can perform many operations simultaneously, thereby saving its time.
- Threads are independent in multithreading. Thus, it doesn't affect other threads, if exception occurs in a single thread.
Multitasking
Multitasking is a process of executing the multiple tasks at the same time. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways, which are,
- Process-based multitasking
Process-based multitasking means multiprocessing, in this, every process has its own memory address and every process allocates separate memory area.
Process is heavy-weight. Cost of communication between the processes is very high. Switching from one process to another process requires some time to save and load the registers, memory maps, update the lists etc. - Thread-based multitasking
Thread-based multitasking means multithreading, in which all the threads share the same address space. Thread is light-weight. Cost of communication between the threads is very low.
At least one process is required for each thread.
Summary
Thus, we learnt, the process of executing the multiple threads concurrently refers to a multithreading in Java and also learn its advantage.