Threads In Java

Threads In Java

What are threads?

Threads allow a program to operate more efficiently by doing multiple things at the same time.

Every java application has at least one thread – the main thread. But from the application point of view – the main is the first java thread and we can create multiple threads from it.

Multithreading refers to two or more threads executing concurrently in a single program

Threads can be used to perform complicated tasks in the background without interrupting the main program.

Life cycle of a thread

image.png

New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread

Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task

Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transition back to the runnable state only when another thread signals the waiting thread to continue executing

Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs

Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates

Ways of creating threads

There are two ways of creating threads -

  1. Extending Thread class
  2. Implementing Runnable interface

Extending Thread class - We need to override the run() method in the Thread class. To start the thread we use the start() method on the thread object which executes a call to the run() method.

image.png

Implementing Runnable Interface -

image.png

Thread priorities

Every Java thread has a priority that helps determine the order in which threads are scheduled. By default, every thread is given priority NORM_PRIORITY (a constant of 5)

MIN_PRIORITY = 1

MAX_PRIORITY = 10

Different Thread methods

image.png

This is the end of the article. Glad you liked.