Multithreading is the ability of a central processing unit (CPU) or a single core in a multi-core processor to execute multipleprocesses or threads concurrently. Java is amulti-threaded programming languageand this means we can create multi-threading applications.
A thread goes through various stages in its life cycle. Like any other resources is created, started, used, and then released. All cycles are:
- New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread.
- Runnable:A thread in this state is considered to be executing its task.
- Blocked:A thread that is blocked waiting for a monitor lock is in this state.
- Waiting:In this state, a thread is waiting indefinitely for another thread to perform a particular action until received the notification to continue.
- Timed waiting:In this state, a thread is waiting for a specific period of timefor another thread to perform a particular action until received the notification to continue or until the time expired.
- Terminated ( Dead ): A runnable thread enters the terminated state when it completes its task or otherwise terminates.
Every thread has a priority that helps the operating system determine the order in which threads are scheduled.Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependent.
Thread class defines three priorities:
- MIN_PRIORITY (1)
- NORMAL_PRIORITY (5)
- MAX_PRIORITY (10)
By default, every thread is given priority NORM_PRIORITY (5), but any value can be used from 1 to 10.