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.
    final boolean isAlive()
  • 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.
      static void sleep (long millisec) throws InterruptedException
    • 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.
      final void join() throws InterruptedException
      final void join(long millisec) throws InterruptedException
    • Notification : threads waits for notification from other threads. The following methods can be used to notify a waiting thread to notify.
      final void notify()
      final void notifyAll()
    • 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.
      final void wait(long timeout) throws InterruptedException
      final void wait(long timeout, int nanos) throws InterruptedException
      final void wait() throws InterruptedException

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.

myThread.setPriority(Math.min(Thread.MAX_PRIORITY, myThread.getPriority()+1));

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.

while (!done()) {
            doLittleBitMore();
            Thread.yield(); 
}

No Responses