Threads in Java – Part II

Different thread states

A thread can be in a different states. once thread’s start() method has been called it does not mean that a thread will start working right away. Several factor determines thread working order and transition. Following are common threads states.

  • Ready to run state : thread starts life in ready to run state
  • Running state : thread is currently executing
  • Dead state : thread can’t run ever again. The following method can be used to determine either a thread is dead or alive.
  • Non runnable states: A running thread can transit to non runable state. A special transition is required to change thread state. A thread don’t go directly to running state, first it has to transit to ready to run state
    • Sleeping : threads sleeps for a certain amount of time. The following method can be used to set a thread to sleep.
    • Blocked for I/O operation: threads waits for I/O operation to complete
    • Join completion: threads waits for other threads to complete task. The following methods can be used to join other threads.
    • Notification : threads waits for notification from other threads. The following methods can be used to notify a waiting thread to notify.
    • Lock Acquisition : thread waits to acquire lock from an object. TThese methods can only be executed on an object whose lock the thread holds, otherwise, it results an exception.

Additional thread methods can be used to prioritize thread to minimum, normal and maximum. The following method can be used to set a max priority to a thread.

A yeild() method can be used to pause current thread and allow other thread to complete first. The following code example gives you a better overview, how to use yield method.

No Responses