Happy Republic Day 2015

MBA I SEM UNIV EXAMS HELD ON 30-JAN,2015

MBA III SEM UNIV EXAMS HELD ON 29-JAN,2015

Tuesday, September 25, 2012

Core Java: Thread Intro & Lifecycle

THREADING

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread and each thread defines a separate path of execution. Thus, multithreading is a specialization form of multi tasking.
There are two distinct types of multitasking: process-based and thread-based. A process is a program that is executing. Thus, process-based multitasking is the feature that allows your computer to run two or more programs concurrently. For example, process based multitasking enables us to run MS-word for editing a word document at the same time running media player to listen some sweet music. In processed based multitasking a program is the smallest unit of code that can be dispatched by a scheduler. (A process migrates between the various scheduling queues throughout its lifetime. The operating system must select, for scheduling purposes, processes from these queues in some fashion. The appropriate scheduler carries out the selection process).
On the other hand in thread-based multitasking system, the thread is the smallest unit of dispatch able code. That is, a single program can perform two or more tasks simultaneously. For instance, a user can simultaneously type in characters and run the spell checker within the same process.
A thread, sometimes called a lightweight process (LWP), because the threads share the common memory space. The memory allocated to the main thread will be shared by all other child threads. Whereas in case of Process the child process are in need to allocate the seperate memory space.
It is a basic unit of CPU utilization; it comprises a thre
ad ID, a program counter, a register set, and a stack. It shares with other threads belonging to the same process its code section, data section, and other operating system resources, such as open files and signals. A traditional (or heavyweight) process has a single thread of control. If the process has multiple threads of control, it can do more than one task at a time. Hence a multitasking thread requires fewer overheads than multitasking processes.

LIFE CYCLE OF A THREAD

During the lifetime of a thread, there are many states it can enter. They include:
  1. Newborn state
  2. Runnable state
  3. Running state
  4. Blocking 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 as shown in the following figure:
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 by using stop( )
If scheduled, it moves to the Runnable state. If we attempt to use any other method at this stage, an exception will be thrown.

Runnable State:
The runnable state means that the thread is ready for execution and is waiting for execution and i.e. for the availability of the processor. That is, the thread has joined the queue of threads that are waiting for execution. Java assigns each thread a priority (an integer) that determines how that thread should be treated with respect to the others. A thread priority is used to decide when to switch from one running thread to the next. This is called context switch. The rule that determine when a context switch takes place are simple:
A thread can voluntarily give up control.
A higher-priority thread can preempt a thread.
In case of threads whit equal priority, some OS’ like Win-98 allocate time-slice automatically for them in round-robin (US tournament in which each competitor plays every other.) fashion. On some other OS’, threads of equal priority must voluntarily yield control to other thread with equal priority. However, if we want a thread to give up control to another thread of equal priority before its turn comes, we can do so by using the yield( ) method.

Running State:
Running means that the processor has given its time to the thread for its execution. The thread runs until it relinquish (v. to give sth. up) control on its own or it is preempted (v. to prevent sth. happening by taking action to stop it) by a higher priority thread. A running thread may relinquish its control in one of the following situation.
  1. 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.
  2. 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 is that the thread is out of queue during this period. The thread re-enters the runnable state as soon as this time period is elapsed.
  3. 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.
Blocking 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 there fully qualified to run again.

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 dead. However, we can kill it by sending to 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.
 
 
                                                                  (or) 
http://www.roseindia.net/java/thread/thread3.gif
Introduction
Every Java program has at least one thread i.e., the main thread. When a Java program starts,
the JVM creates the main thread and calls the program's main() method within that thread.
Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.
Multithreading has several advantages over Multiprocessing such as;
  • Threads are lightweight compared to processes
  • Threads share the same address space and therefore can share both data and code
  • Context switching between threads is usually less expensive than between processes
  • Cost of thread intercommunication is relatively low that that of process intercommunication
  • Threads allow different tasks to be performed concurrently.
Thread Creation
There are two ways to create thread in java;
  • Implement the Runnable interface (java.lang.Runnable)
  • By Extending the Thread class (java.lang.Thread)

 

Implementing the Runnable Interface

The Runnable Interface Signature
public interface Runnable {
void run();
}
One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. We need to override the run() method into our class which is the only method that needs to be implemented. The run() method contains the logic of the thread.


Let us see an example of creating a thread by implementing Runnable interface.
class PrintString
{
    public static void main (String args [ ])
    {
        StringThread t = new StringThread ("Java",50);
        new Thread(t). start ( );
    }


class StringThread implements Runnable
{
    private String str;
    private int num;

    StringThread(String s, int n)
    {
        str  = new String (s);
        num =n;
    }
   
    public void run ( )
    {
        for (int i=1; i<=num; i++)
            System.out.print (str+" ");
    }
}

Creating a Java Thread by extending Thread Class

The class extends a Tread class, it must override run() method of the Thread class. The program may override the other methods also.
To create a thread is to create a subclass of the Thread class. This class must override the run( ) method and it may override the other methods too. Then the class that needs the thread can create an object of the class that extends thread class.
Following listing shows these steps clearly.
class MyThread extends Thread 

{

    MyThread ( ) 

    {

        …………..

        …………..

    }

    

    public void run ( ) //must override

    {

        ………….

        ………….

    }

    ………..

}



public class Example1 

{

    public static void main() 

    {



        MyThread t = new MyThread ();

        ………….

        t.start () ;

        ………….

    }

}

write a program that creates a thread that prints a string n number of times. This program creates the thread by extending thread class:
class PrintString1 

{

    public static void main(String args[]) 

    {

        StringThread1 t = new StringThread1 ("Java",50);

        t.start ( );

    }

}



class StringThread1 extends Thread 

{

    private String str;

    private int num;



    StringThread1 (String s, int n) 

    {

        str=new String (s);

        num=n;

    }

    

    public void run ( ) 

    {

        for (int i=1; i<=num; i++)

            System.out.print(str + " ");

    }

}

LIFE CYCLE OF A THREAD

 During the lifetime of a thread, there are many states it can enter. They include:
  1. Newborn state
  2. Runnable state
  3. Running state
  4. Dead state
  5. Blocking state  
   

  1. New state ? After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.
     
  2. Runnable (Ready-to-run) state ? A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.
     
  3. Running state ? A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.
     
  4. Dead state ? A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.
  5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.