Thread – Lifecycle

Life cycle of a Thread

  1. New
  2. Runnable
  3. Running
  4. Blocked
  5. Terminated

Transition to different stage

  1. New state – In this state when Thread  newthread = new Thread() is called. The thread object is empty  and no system resources are called.
    1. Only start() or stop() can be called on thread in “New”state. Calling other thread methods  will throw IllegalThreadStateException
  2. Runnable state  (Ready state) – Moves to  this state when newThread().start() is called.
    1. start() – Creates system resources to run the thread.
    2. Schedule the thread to run by calling the run() method.
    3. Threads are actually not running when in this state and it is waiting for scheduler to assign it to the process
  3. Running state- When the scheduler chooses the thread from the runnable pool  of thread.
    1. run() method is executed in this state
    2. Calling stop()  will move the thread  to Terminated state 
  4. Blocked state  – Thread goes into this state when
    1. suspend() is called. Resumes when resume() is called
    2. sleep() – Resumes when the time elapses
    3. join()
    4. wait() – Resumes when notify() or notifyAll() is called
    5. blocked in IO – Resumes when IO command completes
  5. Terminated state – Thread can go into this states by 2 ways
    1. Naturally – run() method completes normally
    2. Killed explicitly -invoking  stop()  method.

Flow of thread states

  1. NewThread    can transition to
    1. Runnable – start()
    2. Dead/Terminated state – stop()
  2. Runnable can transition to
    1. Dead/Terminated state – when stop() is invoked  or run()  completes
    2. Blocked State
  3. Running  can transition to
    1. Runnable state – When Yield() is called. But not guaranteed.
  4. Blocked can transition to
    1. Terminated/Dead state – When stop() is invoked
    2. Runnable/Running state – resume(),notify(), notifyAll(),when sleep() time elapses, when IO completes, join() completes.

 


FAQ

  • Can we call start() method multiple times.
    • According to java spec , it is illegal to call start() multiple times. It will throw IllegalThreadStateException

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Cheat Sheet To JAVA Latest Technology

%d bloggers like this: