Multithreading Program in Java

Amansingh Javatpoint
2 min readApr 24, 2021

--

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads. The execution of one thread is independent of another thread. Thus, when some error/ exception is generated in one thread, it does not hamper the process of another thread. All threads of the same process share the same memory space. Multithreading is the process of handling more than one thread simultaneously. The multithreading program in Java demonstrates the usage/ implementation of multithreading in the programming world.

Purpose of Multithreading

Multithreading ensures the maximum utilization of the CPU time when a program is executed. If a program is required to complete more than one task, which is independent of each other, multithreading is required.

Different States of a Thread in Java

The different states of a Thread are:

  • New: A thread whose execution has not started comes in this stage.
  • Runnable: After the start() method is called, the thread is in the queue for processing and ready to run, i.e., the thread scheduler has not selected the thread to move it to the running state. In other words, threads in this stage are waiting for the CPU for execution.
  • Running: The thread scheduler has moved the thread from runnable to this stage, which means the thread gets the CPU, and its execution is started. Note that the Runnable and Running stages form the active state of a thread.
  • Blocked/ Waiting: A thread that is still alive but is not eligible to enter the active state. A thread may enter this stage if a high-priority thread intervenes.
  • Dead/ Terminated: A thread that can no longer be used in a program. Usually, a thread enters this stage when the thread has completed its task or is forcefully terminated.

The following figure depicts the states of a thread.

Creating a Thread in Java

There are two ways to create thread in Java.

1) By inheriting the Thread class

2) By implementing the Runnable Interface

--

--

No responses yet