Introduction to Java Multithreading

To understand this concept one should know about multitasking or multiprogramming concept. In these concept we know that the system can perform more than one task at a time. In multitasking there is single user and a multiprogramming there are number of users performs the number of jobs. According to these concept the java introduced multithreading concept. In multithreading the programmer can divide a single program into multiple parts(tasks). These are implemented by using thread class or by interface runnable.

 

A class inherit the thread class to implement the multithreading concept in a program. This thread class consist of two functions i.e run(), start(). All the set of codes are written in the run() and that method is called by using the start(). There are some other methods which are used with thread are sleep(), wait(), suspend(). These methods are used to run or stop the program according to user requirement. The sleep() is used to stop the functioning for a particular time. When the time is over then that part of program load automatically. In the same way we can place the program into wait(), or can be suspend(). We have to use the method to call them back by using notify(), resume(). Always remember that all set of codes are written in try&catch block.                                              

                                                        CREATING THREAD……

             Threads are implemented in the form of objects that contain a method called run(). It is the only method in which the thread’s behavior can be implemented. A typical run() would appear as follows :

                        public void run()

                        {

                         //. statements ;

                        }

                             Extending Thread Class………

 By extending the class java.lang.Thread we can make our class runnable as threads

             It includes steps :

Step1 :       Declare the class as extending the Thread class.

Step2 :       Implement the run( ) method that is for execution the sequence of code.

Step3 :       Create the thread object and call the start( ) method to initiate the execution.

 

                                     Declaring the class…….

         The Thread class can be extended as :

                                    class MyThread extends Thread

                                    {

                                                . . . . . . . . . .. . .                       

                                                . . . . . . . . . . . . .

                                    }

                                        Starting New Thread…….

      To actually create and run an instance of our thread class, we must write as :

                       

                        MyThread thread = new MyThread( );

                                    thread.start( );

1) instantiates a new object of a class MyThread

2) calls the start() method causing the thread to move into runnable state

 

                               Use of Thread class ……..

       class ABC extends Thread

{

            public void run( )

            {

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

                        {

                                    System.out.println(“ From ThreadABC : i = “ +i);

                        }

            }          

}

class BBB extends Thread

{

public void run( )

            {

                        for( int j=1 ; j<=5 ; j++)

                        {

                                    System.out.println(“ From ThreadBBB : j = “ +j);

                        }

            }          

}

class ThreadTest

{

            public static void main( String aa[ ])

            {

                       new ABC().start( );

                        new BBB().start( );

            }

}

                           Life cycle of a Thread

           Thread goes through various stages in its life cycle. During the life time of a thread, there are many states it can enter. These are :

  1. Newborn state
  2. Runnable state
  3. Running state
  4. Blocked state
  5. Dead state

Newborn state..

   A new thread begins its life cycle in the new stateWhen we create a thread object(Thread th), the thread is born and is said to be in newborn state. At this stage…

  • we can schedule it for running using start( ) method.
  • Or we can kill(stop,finish) it using stop( ) method.

Runnable state..

  •             The runnable state means that the thread is ready for execution and are waiting for the availability of the processor. That is, the thread has joined the queue of threads that are waiting for execution.A thread in this state is considered to be executing its task.

Running state..

            Running means that the processor has given its time to the thread for its execution. A running thread may give-up its control to another in one of the following situations :

         1)Using suspend( ) method a thread is suspended for some time. But it is not killed. A suspended method can be recalled using resume( ) method.

         2)Using sleep( ) method we can put a thread to sleep for a specified time period. This means the thread is out of the queue during this time period. This is recalled automatically after its time period is elapsed

Blocked state..

            A thread is said to be blocked when the thread is suspended(suspend()), sleeping(sleep()), or waiting(wait for some time) in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run again.

Dead state..

            Every thread has its life cycle. A running thread ends its life when run() method has completed its execution. A thread can be killed(stop,finish) as soon it is born, or while it is running, or even when it is in blocked condition

 multithreading in Java

                     Using Thread Methods......

       class ABC extends Threads

{

            public void run( )

            {

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

                        {

                                    if(i==1)                       

                                               yield();

                                    System.out.println (“From thread ABC : i =“ +i);

                        }

            System.out.println( “. . . . .Exit from ABC”);

            }

}

class BB extends Threads

{

            public void run( )

            {

                        for (int j=1 ; j<=5 ; j++)

                        {

                                    System.out.println (“From thread BB : j =“ +j);

                                    if(j==3)                       

                                    stop();//exit execution of this thread

                        }

            System.out.println( “Exit from BB”);

            }

}

class testt

{

            public static void main( String aa[ ])

            {

                        ABC threadAA = new ABC();

                        BB threadBB= new BB();

                        threadAA.start( );

                        threadBB.start( );

            }

}

                         Thread priority.....

   A priority is that , which affects the order in which threads are scheduled for running. These priorities are set by thread scheduler.

To set a thread’s priority, setPriority() method is used, which is a member of Thread class. This is as follows :

                        ThreadName.setPriority (int number);

The int(Integer) number can have the values between 1 and 10.

                         Use of priority in threads

           class A extends Thread

{

            public void run( )

            {

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

                        {

                                    System.out.println (“From Thread AA : i =“ +i);

                               try

                               {

                                   sleep(1000);

                               }

                               catch(Exception excep)

                               {

                       

                                       System.out.println(excep);

                        }

            System.out.println( “. . . . .Exit from AA”);

}

}

}

class BB extends Thread

{

public void run( )

            {

                        for( int j=1 ; j<=10 ; j++)

                        {

                                    System.out.println(“ From Thread BB : j = “ +j);

                                 try

                        {

                        sleep(1000);

                        }

                        catch (Exception error )

                        {

                        System.out.println(error);

                        }                                  

            }

}          

}

class ThreadTestt2

{

            public static void main( String aa[ ])

            {

                       AA threadAA=new AA();                

                        BB threadBB=new BB();

                        threadAA.setPriority (Thread.MIN_PRIORITY);        

                       

threadBB.setPriority (Thread.MAX_PRIORITY);
threadAA.start( );
threadBB.start( );
            }
}

                                   Thread Synchronization

When multiple threads need access to a single resource, there must be a way to ensure that only one thread wil use the resource at any given point of time otherwise it may lead to a severe problem. Foe example, if one thread in a program reads salary from a file and another thread tries to update it, then the program may produce an udesirable output. The solution to this problem can be achieved by using a technique known as synchronization. The objective of synchronization is to control the access to shared resources.

There are two ways to implements synchronization. These are 1)Synchronization methods. 2) Synchronization statements.

When we declare a method synchronized, Java creates a“monitor” and hands it over to the thread that calls the method first time. As long as the thread holds the monitor, no other thread can enter the synchronized section of code.

class first

{

   void call(String msg)

   {

         System.out.println("[" +msg);

         try

         {

           Thread.sleep(1000);

         }

         catch(InterruptedException inexcep)

         {

            System.out.println("Oh!Interupt Exception occur here");

         }

       System.out.println("]");

   }

}

class second implements Runnable

{

String msg;

first f;

Thread t;

public second(first f1,String g)

{

   f=f1;

   msg=g;

   t=new Thread(this);

   t.start();

}

   public void run()

   {

   f.call(msg);

   }

}

class Synchro

{

public static void main(String args[])

{

   first f=new first();

   second s1=new second(f,"Hello");

   second s2=new second(f,"Welcome");

   second s3=new second(f,"Here");

   try

   {

   s1.t.start();

   s2.t.start();

   s3.t.start();

   }

   catch(Exception excep)

   {

     System.out.println("......Interrupted");

   }

}

}

               A Synchronized method

class first

{

   synchronized void call(String msg)

   {

         System.out.println("[" +msg);

         try

         {

           Thread.sleep(1000);

         }

         catch(InterruptedException e)

         {

             System.out.println("Interupt Exception occur here");

         }

       System.out.println("]");

   }

}

class second implements Runnable

{

String msg;

first f;

Thread t;

public second(first f1,String g)

{

   f=f1;

   msg=g;

   t=new Thread(this);

   t.start();

}

   public void run()

   {

   f.call(msg);

   }

}

class Synch

{

public static void main(String args[])

{

   first f=new first();

   second s1=new second(f,"Hello");

   second s2=new second(f,"Welcome");

   second s3=new second(f,"Here");

   try

   {

   s1.t.start();

   s2.t.start();

   s3.t.start();

   }

   catch(Exception e)

   {

     System.out.println("......Interrupted");

   }

}

}

       Implementing Runnable Interface

There are two ways of creating threads : one by using the extending Thread class and another by implementing the Runnable interface. The Runnable interface declares the run() method that is required for implementing threads in our programs. To do this, perform following steps :

  1. Declare the class that implement the Runnable interface.
  2. Implement the run() method.
  3. Create a thread by defining an object that is instantiated from this “runnable” class as the target of the thread.
  4. Call the thread’s start() method to run the thread.

 

class X implements Runnable

{

public void run()

{

            System.out.println(“ “);      

            System.out.println(“Class X implementing Runnable: “);

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

                   {

                        System.out.println(“ “+i);

                     }

            }

}

class RunnableTest

{

   public static void main( String cargu[ ])

            {

                        X obj = new X();

                        Thread threadX = new Thread(obj);

                        threadX.start();

         }

}