Life cycle of a Thread
Transition to different stage
- New state – In this state when Thread newthread = new Thread() is called. The thread object is empty and no system resources are called.
- Only start() or stop() can be called on thread in “New”state. Calling other thread methods will throw IllegalThreadStateException
- Runnable state (Ready state) – Moves to this state when newThread().start() is called.
- start() – Creates system resources to run the thread.
- Schedule the thread to run by calling the run() method.
- Threads are actually not running when in this state and it is waiting for scheduler to assign it to the process
- Running state- When the scheduler chooses the thread from the runnable pool of thread.
- run() method is executed in this state
- Calling stop() will move the thread to Terminated state
- Blocked state – Thread goes into this state when
- suspend() is called. Resumes when resume() is called
- sleep() – Resumes when the time elapses
- wait() – Resumes when notify() or notifyAll() is called
- blocked in IO – Resumes when IO command completes
- Terminated state – Thread can go into this states by 2 ways
- Naturally – run() method completes normally
- Killed explicitly -invoking stop() method.
Flow of thread states
- NewThread can transition to
- Runnable – start()
- Dead/Terminated state – stop()
- Runnable can transition to
- Dead/Terminated state – when stop() is invoked or run() completes
- Blocked State
- Running can transition to
- Runnable state – When Yield() is called. But not guaranteed.
- Blocked can transition to
- Terminated/Dead state – When stop() is invoked
- Runnable/Running state – resume(),notify(), notifyAll(),when sleep() time elapses, when IO completes, join() completes.
- Can we call start() method multiple times.
- According to java spec , it is illegal to call start() multiple times. It will throw IllegalThreadStateException