Wednesday 15 February 2017

Multithreaded Programming in Java ( PART - II )


 Creating Multiple Threads

A Program can spawn as many threads as it needs.

Ex- 
      //Creating Multiple Threads

    class NewThread implements Runnable
  {
     String name;
Thread t;

       NewThread ( String threadname)
       {
           name=threadname;
           t= new thread (this, name);
           System.out.println( " New Thread : " + t);
           t.thread( ) ;
        }
        
         public void run ( )
        {
            try
              {
                  for( int i=5 ;i>0 ; i--)
                   {
                        System.out.println ( name + " : " + i);
                         Thread.sleep(1000);
                    }
             }
            catch ( InterruptException e)
            {
                System.out.println ( name + " Interrupted ");
            }
          System.out.println (name + " Exiting ." );
       }
  }
        class MultiThreadDemo
       {
            public static void main ( String args [] )
             {
                 new NewThread ( " One");
                 new NewThread ( "Two");
                 new NewThread ( "Three");

                    try
                      {
                          Thread.sleep (10000);
                       }
                    catch ( InterruptedException e)
                     {
                         System.out.println ( " Main Thread Interrupted");
                      }
             System.out.println( " Main Thread Exiting ");
        }
 }
              Output:
            New Thread : Thread [one,5,main]
            New Thread : Thread [two,5,main]
            New Thread : Thread [Three,5,main]
            one : 5
            two : 5
            three : 5
            one : 4
             .
             .
             .
            one : 1
            two : 1
            three : 1
            one exiting
            two exiting 
            three exiting
            Main Thread Exiting

Thread Priorities

Thread priorities are used by thread scheduler to decide when each thread should be allowed to run. Also , Higher priority thread gets more CPU time than lower priority threads. A higher priority thread can preempt the lower priority one.

Threads with equal priority should get equal access to the CPU. Threads that share the same priority should yeild control once in a while . This ensures that all threads have a chance to run under a nonpreemptive operating system.


Synchronization

When 2 or more threads need access to a shared resource , they need some way to ensure that the resource will be used by only 1 thread at a time. The process by which this is achieved is called Synchronization.

Key to synchronization is the concept of the monitor ( also called as semaphore ) . A monitor is an object that is used as a mutually exclusive lock , or mutex. Only 1 thread can own a monitor ata given time.

InterThread Communication

Interprocess communication helps to achieve a more subtle level of control. Apart from dividing the program into discrete and logical units , it also provides the benefit of polling.

Polling is usually implemented by a loop that is used to check some condition repeatedly. Once a condition is true , appropriate action is taken. This wastes CPU time.

To avoid polling , java includes an elegant interprocess communication mechanism via wait ( ) ,  notify ( ) and notifyAll ( ) methods. These methods are implemented as final methods in object , so all classes have them.

These methods are described as :

wait () : Tells the calling thread to give up the monitor and goto sleep until some other thread enters.

notify ( ) : wakes up the first thread that called wait ( ) on the same object.

notifyAll ( ) : wakes up all the threads that called wake ( ) on same object.


Deadlock

Deadlock is a condition which occurs  when 2 threads have a circular dependency on a pair of synchronized objects. Deadlock is difficult error to debug for 2 reasons : 

 - It occurs only rarely , when the 2 threads time slice in just the right away.

 - It may involve more than 2 threads and 2 synchronized objects.


                                                                        By: Knowledge Bits




No comments:

Post a Comment

Video of the Day

Contact us

Name

Email *

Message *