Core Java - [Thread Life Cycle]

♠ Posted by Unknown in at 01:52

Thread Life Cycle and Example


During the life time of a thread, there are many states it can enter. They include:
1.      Newborn State
2.      Runnable State
3.      Running State
4.      Blocked State
5.      Dead State

A thread is always in one of these five states. It can move from one state to another via a variety of ways. Shown in below figure.

Image: Java Thread Life Cycle

1.      Newborn State :

When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state, we can do only one of the following things with it:
·         Schedule it for running using start() method.
·         Kill it using stop() method.

2.      Runnable State :

The runnable state means that the thread is ready for execution and is waiting for the availability of the processor. That is the thread has joined the queue of threads that are waiting for execution. If all threads have equal priority, then they are given time slots for execution in round robin fashion, i.e. first-come, first-serve manner. The thread that relinquishes control joins the queue at the end and again waits for its turn. This process of assigning time to threads is known as time-slicing.
However, if we cant a thread to relinquish control to another thread of equal priority before its turn comes, we can do so by using the yield() method.

3.      Running State :

Running means that the processor has given its time to the thread for its execution. The thread runs until it relinquish its control in one of the following situations.
·         It has been suspended using suspend() method. A suspended thread can be revived by using the resume() method. This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it.
·         It has been made to sleep, we can put a thread to sleep for a specified time period using the method sleep(time) where time is in milliseconds. This means that the thread is out of the queue during this time period. The thread re-enters the runnable state as soon as this time period is elapsed.
·         It has been told to wait until some event occurs. This is done using the wait() method. The thread can be scheduled to run again using the notify() method.

4.      Blocked State :

A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. this happens when the thread is suspended, sleeping, or waiting in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run again.

5.      Dead State :

Every thread has a life cycle. A running thread ends its life when it has completed executing its run() method. It is a natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death to it. A thread can be killed as soon it is born, or while it is running, or even when it is in “not runnable” (blocked) condition.

When we start any Java Program, one thread begins running immediately, which is called the "main thread" of that program. Within the main thread of any Java program you can create other "child" threads.
The Main thread is created automatically when your program is started. The main thread of Java Programs is controlled through an object of "Thread" Class.

The multithreaded programming in Java is built upon the "Thread Class", its methods and its companion Interface "Runnable". To create a new thread, your program will either extend "Thread" class or implement the "Runnable" interface.

Thread Class Methods :


Some commonly used methods of Thread class are given below:

1. currentThread() :
            Returns reference to the currently executing thread object.
2. getName() :
            Returns the name of the thread in which it is called.
3. getPriority() :
            Returns the Thread's priority
4. interrupt() : Used for Interrupting the thread.
5. interrupted() : Used to check whether the current thread has been interrupted or not.
6. isAlive() : Used for testing whether a thread is alive or not.
7. setName() : Changes the name of the thread to NewName.
8. setPriority() : Changes the priority of thread.
9. sleep() :  Causes the currently executing thread to sleep for the specified number of microsecond.
10 start() : Used to begin execution of thread. The java virtual machine calls the run method of the thread in which this method is called.
11. toString() : Returns a string represntation of thread.
12. yield() : Used to pause temprarily to currently executing thread object and allow other threads to execute.
13. activeCount() : Returns the number of active threads in the current thread's thread group.
14. destroy() : Destroys the thread without any cleanup.

Example :

import java.io.*;
import java.lang.*;
class MyThread implements Runnable
{
            private char c;
            private int times;
           
            public MyThread(char x, int n)
            {
                        c = x;
                        times = n;
            }

            public void run()
            {
                        for(int i = 1; i<= times; i++)
                        {
                                    System.out.println(c + " character is " + i + " times....");
                        }
            }
};
public class  ThreadExample
{
            public static void main(String[] args)
            {
                        MyThread th1 = new MyThread('A',10);
                        MyThread th2 = new MyThread('B',10);

                        th1.setPriority(Thread.MIN_PRIORITY);
                        th2.setPriority(Thread.MAX_PRIORITY);

                        th1.start();
                        th2.start();
            }
}



0 comments:

Post a Comment