J2EEOnlineJ2EE





Java Multitasking  «Prev  Next»
Lesson 7The life cycle of a thread
ObjectiveList the states of a thread in Java

Life Cycle of a Java Thread

Describe the ways to move a thread from one state to another.

Threads run as part of the system and perform tasks simultaneously and it is difficult to know how they behave. In addition, Java threads have definite life cycles.

Thread Lifecycle

Let us start by looking at the lifecycle of an application thread. Every operating system has a view of threads that can differ in the details (but in most cases is broadly similar at a high level). Java tries hard to abstract these details away, and has an enum called Thread.State.
The values of Thread.State provide an overview of the lifecycle of a thread:


Thread life cycles

  1. NEW: The thread has been created but its start() method has not yet been called. All threads start in this state.
  2. RUNNABLE: The thread is running or is available to run when the operating system schedules it.
  3. BLOCKED: The thread is not running because it is waiting to acquire a lock so that it can enter a synchronized method or block. We will see more about synchronized methods and blocks later in this section.
  4. WAITING: The thread is not running because it has called Object.wait() or Thread.join().
  5. TIMED_WAITING - (Sleeping, Waiting): The thread is not running because it has called Thread.sleep() or has called Object.wait() or Thread.join() with a timeout value.
  6. TERMINATED: The thread has completed execution. Its run() method has exited normally or by throwing an exception.

Thread States in a Nutshell
States of a thread in Java