Java Tutorial

Multi Threading

Thread:

  1. A flow of control is known as thread.
  2. If a program contains multiple flow of controls for achieving concurrent execution then that program is known as multi threaded program.
  3. A program is said to be a multi threaded program if and only if in which there exist 'n' number of sub-programs there exist a separate flow of control. All such flow of controls are executing concurrently such flow of controls are known as threads and such type of applications or programs is called multi threaded programs.

The languages like C, C++ comes under single threaded modeling languages, since there exist single flow of controls where as the languages like JAVA, DOT NET are treated as multi threaded modeling languages, since there is a possibility of creating multiple flow of controls.

When we write any JAVA program there exist two threads they are fore ground thread and back ground thread.

Fore ground threads are those which are executing user defined sub-programs where as back ground threads are those which are monitoring the status of fore ground thread. There is a possibility of creating 'n' number of fore ground threads and always there exist single back ground thread.

Multi threading is the specialized form of multi tasking of operating system.

In information technology we can develop two types of applications. They are process based applications and thread based applications.

Process Based ApplicationsThread Based Applications
1. It is the one in which there exist single flow of control.1. It is the one in which there exist multiple flow of controls.
2. All C, C++ applications comes under it.2. All JAVA, DOT NET applications comes under it.
3. Context switch is more (context switch is the concept of operating system and it says switching the control from one address page to another address page).3. Context switch is very less.
4. For each and every sub-program there exist separate address pages.4. Irrespective of 'n' number of sub-programs there exist single address page.
5. These are treated as heavy weight components.5. These are treated as light weight components.
6. In this we can achieve only sequential execution and they are not recommending for developing internet applications.6. In thread based applications we can achieve both sequential and concurrent execution and they are always recommended for developing interact applications.

States of a thread:

When we write any multi threading applications, there exist 'n' numbers of threads. All the threads will under go different types of states. In JAVA for a thread we have five states. They are new, ready, running, waiting and halted or dead state.

New state:

It is one in which the thread about to enter into main memory.

Ready state: It is one in which the thread is entered into memory space allocated and it is waiting for CPU for executing.

Running state: A state is said to be a running state if and only if the thread is under the control of CPU.

Waiting state:

It is one in which the thread is waiting because of the following factors:

  1. For the repeating CPU burst time of the thread (CPU burst time is an amount of the required by the thread by the CPU).
  2. Make the thread to sleep for sleep for some specified amount of time.
  3. Make the thread to suspend.
  4. Make the thread to wait for a period of time.
  5. Make the thread to wait without specifying waiting time.

Halted state:

It is one in which the thread has completed its total execution.

As long as the thread is in new and halted states whose execution status is false where as when the thread is in ready, running and waiting states that execution states is true.

Creating a thread:

In order to create a thread in JAVA we have two ways. They are by using java.lang.Thread class and by using java.lang.Runnable interface.

In multi threading we get only one exception known as java.lang.InterruptedException.

Using java.lang.Thread:

Creating a flow of control in JAVA is nothing but creating an object of java.lang.Thread class. An object of Thread class can be created in three ways. They are:

  1. Directly Thread t=new Thread ();
  2. Using factory method Thread t1=Thread.currentThread ();
  3. Using sub-class of Thread class
class C1 extends Thread
{
    ..............;
    ..............;
};
C1 o1=new C1 (); 
Thread t1=new C1 ();
Here, C1 is the sub-class of Thread class.

Thread API:

public static final int MAX_PRIORITY (10); 
public static final int MIN_PRIORITY (1); 
public static final int NORM_PRIORITY (5);

The above data members are used for setting the priority to threads are created. By default, whenever a thread is created whose default priority NORM_PRIORITY.

Constructors:

i) Thread (): With this Constructor we can create an object of the Thread class whose default thread name is Thread-0.

For Example:

Thread t=new Thread ();
System.out.println (t.getName ());// Thread-0

ii) Thread (String): This Constructor is used for creating a thread and we can give the user specified thread name.

For Example:

Thread t=new Thread ("JAVA"); 
t.setName ("JAVA");
t.setPriority (Thread.MAX_PRIORITY);

iii) Thread (Runnable): This Constructor is used for converting Runnable object into Thread object for entering into run method of Runnable interface by making use of start method of Thread class without giving thread name.

iv) Thread (Runnable, String): This Constructor is similar to above Constructor but we give thread name through this Constructor.

Instance methods:

public final void setName (String); 
public final String getName ();

The above two methods are used for setting the name of the thread and getting the name from the thread respectively.

For Example:

Thread t1=new Thread (); 
T1.setName ("JAVA"); 
String tp=t1.getName ();
System.out.println (tp);// JAVA
public final void setPriority (int); 
public final int getPriority ();

The above two methods are used for setting the priority to the thread and getting the priority of the thread respectively.

For Example:

Thread t1=new Thread (); Int pri=t1.getPriority ();
System.out.println (pri);// 5 7 by default 
t1.setPriority (Thread.MAX_PRIORITY); 
pri=t1.getPriority ();
System.out.println (pri); // 10

public void run ():

Any JAVA programmer want to define a logic for the thread that logic must be defined only run () method. When the thread is started, the JVM looks for the appropriate run () method for executing the logic of the thread. Thread class is a concrete class and it contains all defined methods and all these methods are being to final except run () method. run () method is by default contains a definition with null body. Since we are providing the logic for the thread in run () method. Hence it must be overridden by extending Thread class into our own class.

For Example:

class C1 extends Thread
{
    public void run ()
    {
        ...............;
        ...............;
    }
};

public finalvoid start():

This is the method which is used for making the Thread to start to execute the thread logic. The method start is internally calling the method run ().

For Example:

Thread t1=new Thread (); 
t1.start ();
Thread t2=Thread.currentThread ();
t2.start ();

public finalvoid suspend ():

This method is used for suspending the thread from current execution of thread. When the thread is suspended, it sends to waiting state by keeping the temporary results in process control block (PCB) or job control block (JCB).

For Example:

public finalvoid resume ():

This method is used for bringing the suspended thread from waiting state to ready state. When the thread is resumed to start executing from where it left out previously by retrieving the previous result from PCB.

public finalvoid stop ():

This method is used to stop the execution of the current thread and the thread goes to halted state from running state. When the thread is restarted it starts executing from the beginning only.

public finalvoid wait(longmsec):

This method is used for making the currently executing thread into waiting state for a period of time. Once this period of time is over, automatically the waiting thread will enter into ready state from waiting state.

Static methods:

i) public static void sleep (long msec) throws InterruptedException method is used (waiting state). If the sleep time is over automatically thread will come from waiting state to ready state.

For Example:

Thread.sleep (1000);

ii) public static Thread currentThread () is used for obtaining the threads which are running in the main memory of the computer.

For Example:

Thread t=Thread.currentThread ();
System.out.println (t);// Thread [main (fat), 5, main (bat)]

Write a JAVA program to find the threads which are running internally and print priority values?

Answer:

class ThDemo
{
    public static void main (String [] args)
    {
        Thread t=Thread.currentThread (); 
        System.out.println (t);  
        t.setName ("ABC"); System.out.println (t);
        System.out.println ("IS IT ALIVE..?"+t.isAlive ());// true
        Thread t1=new Thread ();// new state
        System.out.println ("IS IT ALIVE..?"+t.isAlive ());// false 
        System.out.println ("DEFAULT NAME OF THREAD = "+t1.getName ());// Thread-0 
        System.out.println ("MAXIMUM PRIORITY VALUE = "+Thread.MAX_PRIORITY);// 10 
        System.out.println ("MINIMUM PRIORITY VALUE = "+Thread.MIN_PRIORITY);// 1 
        System.out.println ("NORMAL PRIORITY VALUE = "+Thread.NORM_PRIORITY);// 5
    }
};

Output:

Thread[main,5,main] 
Thread[ABC,5,main] 
IS IT ALIVE..?true 
IS IT ALIVE..?true
DEFAULT NAME OF THREAD = Thread-0
MAXIMUM PRIORITY VALUE = 10
MINIMUM PRIORITY VALUE = 1 
NORMAL PRIORITY VALUE = 5

Instance methods:

public boolean isAlive () method is used for checking whether the thread is executing or not. It returns 'true' as long as the thread is in ready running and waiting states. It returns 'false' as long as the thread is in new and halted state.

Write a thread program which displays 1 to 10 numbers after each and every 1 second.

Answer:

class Th1 extends Thread
{
    public void run ()
    {
        try
        {
            for (int i=1; i<=10; i++)
            {
                System.out.println ("VALUE OF I = "+i); 
                Thread.sleep (1000);
            }
        }
        catch (InterruptedException ie)
        {
            System.out.println (ie);
        }
    }
};
class ThDemo1
{
    public static void main (String [] args)
    {
        Th1 t1=new Th1 ();
        System.out.println ("IS T1 ALIVE BEFORE START = "+t1.isAlive ());
        t1.start ();
        System.out.println ("IS T1 ALIVE AFTER START = "+t1.isAlive ());
    }
};

Output:

IS T1 ALIVE BEFORE START = false 
IS T1 ALIVE AFTER START = true 
VALUE OF I = 1
VALUE OF I = 2
VALUE OF I = 3 
VALUE OF I = 4 
VALUE OF I = 5 
VALUE OF I = 6 
VALUE OF I = 7 
VALUE OF I = 8 
VALUE OF I = 9 
VALUE OF I = 10

Re-write the above program using runnable interface.

Answer:

class Th1 implements Runnable
{
    public void run ()
    {
        try
        {
            for (int i=1; i<=10; i++)
            {
                System.out.println ("VALUE OF I = "+i); Thread.sleep (1000);
            }
        }
        catch (InterruptedException ie)
        {
            System.out.println (ie);
        }
    }
};
class ThDemo2
{
    public static void main (String [] args)
    {
        Runnable t=new Th1 ();
        Thread t1=new Thread (t, "ABC");
        System.out.println ("THREAD NAME = "+t1.getName ()); 
        System.out.println ("IS T1 ALIVE BEFORE START = "+t1.isAlive ()); 
        t1.start ();
        System.out.println ("IS T1 ALIVE AFTER START = "+t1.isAlive ());
    }
};

Output:

THREAD NAME = ABC
IS T1 ALIVE BEFORE START = false
IS T1 ALIVE AFTER START = true
VALUE OF I = 1 
VALUE OF I = 2 
VALUE OF I = 3 
VALUE OF I = 4 
VALUE OF I = 5 
VALUE OF I = 6 
VALUE OF I = 7 
VALUE OF I = 8 
VALUE OF I = 9 
VALUE OF I = 10

Write a JAVA program which produces 1 to 10 numbers in which even numbers are produced by one thread and odd numbers are produced by another thread.

Answer:

class Th1 extends Thread
{
    public void run ()
    {
        try
        {
            for (int i=1; i<=10; i+=2)
            {
                System.out.println ("VALUE OF ODD : "+i); 
                Thread.sleep (1000);
            }
        }
        catch (InterruptedException ie)
        {
            System.out.println (ie);
        }
    }
};
class Th2 implements Runnable
{
    public void run ()
    {
        try
        {
            for (int j=2; j<=10; j+=2)
            {
                System.out.println ("VALUE OF EVEN : "+j); 
                Thread.sleep (1000);
            }
        }
        catch (InterruptedException ie)
        {
            System.out.println (ie);
        }
    }
};
class ThDemo6
{
    public static void main (String [] args)
    {
        Th1 t1=new Th1 ();// object of Thread class
        Th2 t2=new Th2 ();// object of Runnable class
        Thread t=new Thread (t2);// Runnable is converted into Thread object 
        System.out.println ("BEFORE START T1 IS : "+t1.isAlive ()); 
        System.out.println ("BEFORE START T2 IS : "+t.isAlive ()); 
        t1.start ();
        t.start ();
        System.out.println ("AFTER START T1 IS : "+t1.isAlive ());
        System.out.println ("AFTER START T2 IS : "+t.isAlive ());
        try
        {
            t1.join ();// to make thread to join together for getting performance
            t.join ();
        }
        catch (InterruptedException ie)
        {
            System.out.println (ie);
        }
        System.out.println ("AFTER JOINING T1 IS : "+t1.isAlive ()); 
        System.out.println ("AFTER JOINING T2 IS : "+t.isAlive ());
    }
};

Output:

BEFORE START T1 IS : false 
BEFORE START T2 IS : false 
AFTER START T1 IS : true 
AFTER START T2 IS : true 
VALUE OF ODD : 1
VALUE OF EVEN : 2
VALUE OF ODD : 3 
VALUE OF EVEN : 4 
VALUE OF ODD : 5 
VALUE OF EVEN : 6 
VALUE OF ODD : 7 
VALUE OF EVEN : 8 
VALUE OF ODD : 9 
VALUE OF EVEN : 10
AFTER JOINING T1 IS : false 
AFTER JOINING T2 IS : false

public void join () Throws Interrupted Exception:

This method is used for making the fore ground threads to join together so that JVM can call the garbage collector only one time for collecting all of them instead of collecting individually.

How a thread executes internally?

Answer:

Thread executes