What is thread in Java? Difference between process and thread? Life cycle of thread.
The thread is a lightweight process that means one single program can be divided into small threads which will execute concurrently for fast execution of task. We can say that thread is a sub process of a process.
A thread is an independent path of execution within a program. Many thread can run concurrently within a program. Every threads in Java is created and controlled by the java.lang thread class. A java program can have many threads, and these threads can run currently, either synchronously or asynchronously.
- Threads are lightweight compared to process.
Difference between thread and process
Process | Thread |
---|---|
- A Process is an instance of a program. It contains a threads. | - Threads are the parts of process. It cannot contain a process. |
- Process run in its separate. | - Thread run in shared memory spaces. |
- Process is controlled by the operating system. | - Threads a re controlled by programmer in a program. |
- Processes are independent. | - Threads are dependent. |
- New processes require duplication of the parent process. | - New threads are easily created. |
- Process require more time for context switching as they are more heavy. | - Threads require less time for context switching as they are lighter then process. |
- Process require more resources then threads. | - Threads generally need less resources than process. |
- Process require more time for termination. | - Threads require less time for termination. |
Life cycle of threads
New
The thread is in new state if you create an instance of thread class but before the invocation of start() method.
Runnable
A thread in the runnable state is executing the Java virtual machine but it may be waiting for other resources from the operating system such as processor.
Running
The thread is in running state if the thread scheduler has selected it.
Blocked (Non Runnable)
It is the state when the thread is still alive, but is currently not eligible to run.
Terminated
A thread is in terminated or dead state when its run() method exists.