Course Content‎ > ‎Session 10‎ > ‎

Threads

Life Cycle of a Thread

A thread moves through several states from its creation to death. These states are:

    1. New - immediately after a thread is created, but it hasnt been started as
       yet.
    
    2. Runnable - a thread can be run, when the time slicing mechanism has CPU
       cycles available for the thread. Thus, the thread might or might not be
       running.
    
    3. Running - When the JVM selects it for execution.
    
    4. Blocked - the thread could be run, but theres something that prevents it.
    
    5. Dead - when the thread completes. The normal way for a thread to die is by
       returning from its run() method (given below).  

       

                         Life Cycle of a Thread

Thread class

Constructors

There are four constructors for the Thread class:

    Thread()
    
    Thread (Runnable)
    
    Thread (String)
    
    Thread (Runnable, String)

The Thread constructors create an instance of the Thread class, allowing the object to be run concurrently with other objects. When creating a thread, you can either create the thread by subclassing Thread itself or if you have a class that implements Runnable, pass that class to the Thread constructor, which will then create a thread out of that class. Passing a String to the constructor allows you to create references to the individual threads, which can then be used as references. For example, if you have created several instances of the same thread, you could give them distinctive names to keep track of them.

Methods

The following are some useful methods for determining a threads status and controlling the execution of the thread:

    currentThread()  returns the currently executing thread
    
    isAlive()  checks to see, if the thread is active
    
    suspend()  suspends the execution of the thread
    
    resume()  resumes execution of a suspended thread
    
    sleep(int)  causes the thread to sleep for int milliseconds
    
    yield()  causes the thread to give up execution to waiting threads  

Creation and Execution of Threads

In Java, there are two ways to create a class that can be multithreaded:

    1. Create a class that extends the Thread class
    
    2. Create a class that implements the Runnable interface

Execution of a thread

To execute a thread, the thread is first created and then the start() method is invoked on the thread. Eventually the thread would execute and the run() method would be invoked.  

Example illustrating the creation and execution of a thread:

1. You can create a thread by extending Thread with your own class and overriding the run() method.
    
    class className extends Thread
    {
        public void run()
        {
            //Thread body of execution
        }
    }

Here is an example to illustrate the above:  

    public class simpleThread extends Thread
    {
        private int countDown = 5;
        private int threadNumber;    
        private static int threadCount = 0;    
        
        public simpleThread()    
        {        
            threadNumber = ++threadCount;        
            System.out.println("Making "+ threadNumber);        
        }
        
        public void run()    
        {        
            while (true)            
            {
                System.out.println("Thread "+ threadNumber + " ( "+countDown + " ) "); 
                
                if(--countDown == 0)
                    return;            
            }        
        }
        
        public static void main (String[] args)    
        {        
            for(int i = 0; i < 5; i++)            
                new simpleThread().start();
            
            System.out.println("All threads started");        
        }    
    }
    
The output of this program will look like this:

    C:\TEMP>java simpleThread
    Making 1
    Making 2
    Making 3
    Making 4
    Making 5
    All threads started
    Thread 1 ( 5 )
    Thread 1 ( 4 )
    Thread 1 ( 3 )
    Thread 1 ( 2 )
    Thread 1 ( 1 )
    Thread 2 ( 5 )
    Thread 2 ( 4 )
    Thread 2 ( 3 )
    Thread 2 ( 2 )
    Thread 2 ( 1 )
    Thread 3 ( 5 )
    Thread 3 ( 4 )
    Thread 3 ( 3 )
    Thread 3 ( 2 )
    Thread 3 ( 1 )
    Thread 4 ( 5 )
    Thread 4 ( 4 )
    Thread 4 ( 3 )
    Thread 4 ( 2 )
    Thread 4 ( 1 )
    Thread 5 ( 5 )
    Thread 5 ( 4 )
    Thread 5 ( 3 )
    Thread 5 ( 2 )
    Thread 5 ( 1 )
    C:\TEMP>

In this program, you see that the threads are not run in the order they are created. The order that the CPU attends to an existing set of threads is indeterminate, unless you adjust the priorities using Threads setPriority() method. run() method always has some kind of loop that continues, until the thread is no longer needed; so you must establish the condition to break out of the loop. For example, return() in the above program.

2. You can have your class implement the Runnable interface for creating threads:

    class className implements Runnable
    {
        public void run()
        {
            ...
        }
    }

A class that has implemented the Runnable interface can be run in a thread by passing the instance of the class to a new Thread object.

    className instanceName = new className();
    
    new Thread(instanceName).start();
    
    Here is an example illustrating this:
    
    class ThreadRunnableConstructor implements Runnable
    {
        Thread myThread;
        public void run()
        {
            System.out.println("Hello from ThreadRunnableConstructor thread");
        }
        
        ThreadRunnableConstructor()
        {
            myThread = new Thread(this);
            myThread.start();
        }
        
        public static void main(String args[])
        {
            new ThreadRunnableConstructor();
        }
    }

Its output would be:

    C:\TEMP>java ThreadRunnableConstructor
    Hello from ThreadRunnableConstructor thread

Comments