The first concept to define is that of the process. Processes is program that is executing. Multiple process may run concurrently in CPU. The multitasking is feature of O/S where more than one process can be executed.
Threads are fundamental unit of dispatchable code. A process can have multiple threads. In other words thread s are light weight processes. These threads can be executed concurrently. Threads increase utilization of CPU cycles.
Advantage of Threads over Processes
- Threads are light weight tasks so they don't require there own address space but they threads of same processes share same address space whether process are heavyweight hence they need their own address space.
- Interprocess communication of processes are expensive and limited. But interthread communication is inexpensive.
- Context switching of processes are costly whether context switching of threads are inexpensive.
Thread Life cycle is given below:
This life cycle is same as life cycle of process. Thread created then it goes in state runnable means thread is ready to run. Then it goes to state running. If any other thread with high priority came or it is waiting for some resources then it blocked. After accomplishing task it goes into dead state. From blocked state it will go to dead state if it killed by O/S forcefully.
The main thread is first thread that is running since beginning of prorgramm. It is important because
- Other child Threads spawned from it.
- This is last thread to finish execution and perform all shutdown action.
Thread implemented by java either using Thread class or using Runnable interface.