Multi-Threading in Java

In this tutorial, we will learn about Multi-Threading in Java. In java we can run more than one threads(a piece of code) simultaneously at the same time with the help of Multithreading and each piece code can perform a different task. Here thread means a lightweight process which can perform some task in the program. It is important to note that, in multithreading, all the threads share common resources(CPU). Before joining further let’s check out the life cycle of a thread.

Life Cycle of a Thread:

Every thread in Java goes through various stages all these all states together known as a life cycle of a thread. Check out the following illustration to see the life cycle of a thread.

Multi-Threading in Java

Now we will learn about each states of Life Cycle of Thread.

  • Newborn: when we create a thread object. Then thread enters in the newborn state. After this, we use the start() method to start a newborn thread.
  • Runnable: In this state, the thread is ready to run and waiting for the availability of the resources. In case all the threads in the program have equal priority then they will get time slots for execution First Come First Serve manner.
  • Running: This is the state when a thread is running.
  • Blocked: In case a thread is prevented to enter in running or runnable state also not dead it means the thread is in block statement. There are various methods which can move a thread into this blocked state such as suspend(), sleep(milliseconds), wait(). A thread can beck enter into running or runnable state from this state with the help of resume() and notify() methods.
  • Dead: This is the last stage in the life cycle of a thread. If a thread completed executing it’s run() method, it is known as a natural death. But we can kill a thread using stop() method.

Thread Priorities:

We can set priority to each thread. When we set the priority of thread it helps thread scheduler to decide the order in which all the threads will run. Threads with high priority get the allocation of processor time before lower-priority threads. There is a total of three constants available in Thread class and we can use these constants to set the priority of Thread.

  • MIN_PRIORITY
  • NORM_PRIORITY
  • MAX_PRIORITY

This was a theory tutorial of Multithreading. In the next tutorial, we will create thread program so keep continue with the next tutorial.

Spread the love
Scroll to Top
×