Saturday, July 26, 2014

What is Thread in Java


So what exactly is a thread? In Java, "thread" means two different things:


  •  An instance of class java.lang.Thread
  •  A thread of execution

An instance of Thread is just like an object. Like any other object in Java, it has variables and  methods, and lives and dies on the heap. But a thread of execution is an individual process (a "lightweight" process) that has its own call stack. In Java, there is one thread per call stack or, to think of it in reverse, one call stack per thread. The main() method, that starts the whole execution , runs in one thread, called the main thread.


Life Cycle of Thread (Thread State):

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The life cycle of a thread is maintained by JVM.

      

New : A thread begins its life cycle in the new state. It remains in this state until the start() method is called on it. It is also referred to as a born thread.

Runnable : The Thread is in runnable state when start() method is called. It will remain in the runnable state until the thread scheduler picks the thread into running state.

Running : This is the actual running state of the thread. It happens when thread scheduler chosen the thread from runnable state.

Blocked : This is the state when the thread is alive but not in the running state. When it resume it directly goes to the runnable state not in running state.

Terminated: thread is terminated or in dead state. This state arrives when run() method exits or completed the task.

Thread Scheduler :


  •  The thread scheduler is the part of the JVM,that decides which thread should run at any given moment, and also takes threads out of the run state.
  •  And it's the thread scheduler that decides which thread of all that are eligible(runnable state) will actually run.
  •  Any thread in the runnable state can be chosen by the scheduler to be the one and only running thread.
  • The order in which runnable threads are chosen to run is not guaranteed.

No comments :

Post a Comment