Sunday 12 February 2017

MultiThreaded Programming in Java ( PART - II )


                                                   
MultiThreaded Programming in Java ( PART - II )


 Synchronization

Since multithreading introduces an asynchronous behaviour to your programs , there must be a way for you to enforce synchronicity when you need it.

In order to prevent conflict between 2 threads we use the monitor. The monitor is a control mechanism first defined by C.A.R Hoare . Monitor can be considered as very small box which can hold only 1 thread.

So , a monitor can be used to protect a shared asset from being manipulated by more than 1 thread at a time.


Messaging

After you divide your program into separate threads , you need to define how they will communicate with each other. Java's provide a clean , low cost way for two or more threads to talk to each other , via calls to predefined methods that all objects have.

Java's messaging system allows a thread to enter a synchronized method on an object and then wait there untill some other thread explicitly notifies it to come out.


The  main Thread

When a java program starts up , one thread begins running immediately. This is the main thread of the program , because it is the one that is executed when your program begins.

It is important :

- It is the thread from which other child threads will be spawned.

- It must be the last thread to finish the execution because it performs the various shutdown actions.

It's general form is :

    static Thread currentThread ()

 // controlling the main thread 
  
   class CurrentThreadDemo
 {
    public static void main ( String [] args )
   {
      Thread t = Thread.currentThread () ;

         System.out.println (" Current thread  :" + t);
          t.setName(" My Thread ");
        System.out.println ( " After name change : " + t);

     try
    {
         for ( int n=5 ; n> 0 ; n--)
         {
             System.out.println(n);
                Thread.sleep(1000);
         }
   }
    catch ( InterruptedException e)
    {
      System.out.println (" Main thread interrupted" );
    }
  }
}
                 Output:
            curent Thread : Thread(main,5,main)
          After name change : Thread ( My Thread,5,main)
          5
          4
          3
          2
          1


Creating Thread

You create a thread by instantiating an object of type Thread. Java defines 2 ways in which this can be accomplished :

  - By Implementing  Runnable interface.
  - By Implementing Thread Class.




No comments:

Post a Comment

Video of the Day

Contact us

Name

Email *

Message *