In concurrent programming, there are two basic units of execution: processes and threads. Java provides inbuilt support with the concept of multithreading with the rich APIs.
- A thread is a lightweight sub-process and smallest unit of processing.
- Like a process, a thread also provides an execution environment.
- A thread requires fewer resource than creating a new process.
- A thread exists within a process and uses process’s resource including memory and open files.
- Thread is said to be independent and has separate path of execution.
Mulithreading in java
- Multithreading in java is a mechanism to run multiple threads simultaneously.
- Multithreading in java is used to achieve multitasking.
- Multithreading is generally used for games, animations, etc.
Multitasking is the ability of performing more than one task simultaneously (at the same time). It is used to increase the overall throughput of the system. It means to increase the CPU utilization. Multitasking can be achieved in two ways:
- Process based multitasking (Multiprocessing)
- Thread based multitasking (Multithreading)
1. Process based multitasking ( Multiprocessing )
- A process is an instance of a program running inside a computer.
- A process has a self contained execution environment.
- Each process has it own memory space.
- During process creation, it needs more resources than a thread.
- Cost of communication between the process is high.
- A process contains one or more different threads.
2. Thread based multitasking ( Multithreading )
- A thread is a lightweight sub process.
- A thread also is a self contained execution environment.
- Thread shares the common memory space of the process in which they are contained.
- Thread requires fewer resources than creating a new process.
- Cost of communication between the thread is low.
- A thread always resides under a process.
Advantages of Java Multithreading
- Increases overall performance and saves time because of parallel execution of multiple threads simultaneously.
- Threads do not affect other threads if there occurs any exception, because they have separate execution path.
- Threads reduces the cost of maintenance.
- Threads requires less resources than any process when it it being created.
- Multithreading provides better use of cache storage by proper utilization of different resources.
Important application areas of Multithreading
- To develop multimedia graphics.
- To develop animations.
- To develop video games.
- To develop web servers and application servers. (Every web server & application server uses the concept of mulithreading to handle the requests simultaneously.)