Multithread Programming in Java

Introduction

Threads are defined as small parts or sections of a large program. As the name suggests, Multithreading involves two or more such threads. The concept of Multithreading is a Java feature wherein two or more threads are concurrently executed such that maximum CPU utilization can be achieved. As threads are smaller parts of the program, they are lightweight processes that give way to bigger ones.

Thread Life Cycle

Each thread follows a pattern to complete its life cycle. It starts with the thread being created. It is then initialized or started. The thread then executes a particular task and finally dies. The stages of threads are described below:

  • New () – This is a newly created thread more generally referred to as a born thread. This is the first stage in the thread cycle and the thread remains in such a manner until the program starts it.
  • Runnable () – A thread reaches the runnable stage when it is started after its birth. During the runnable phase, a thread is considered to be performing a task.
  • Waiting () – If a thread is linked to another thread and can only perform when that thread has finished execution, it does into this waiting state. Once it receives information from the dependent thread, it changes its state back to runnable.
  • Timed Waiting () – When there is a time-limited waiting period for a thread, it reaches the timed waiting stage of its cycle. Once the wait is over, it becomes runnable again.
  • Terminated (dead) – When a thread has completed its task and is no longer useful to the execution of the program, it becomes a dead thread.

Thread Priority

Threads are marked according to their priority. A thread with a higher priority is executed before a thread with low priority. Priority ranges from MIN_PRIORITY (constant of 1) to MAX_PRIORITY (constant of 10). By default, threads are given NORM_PRIORITY (constant of 5).

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.