Publish your story - poem - jokes free online--click here

JAVA

Synchronization of Thread In Java

 Synchronization of Thread In Java

                  Since java supports multithreading, hence it’s simply possible that there may be a common object which is shared by more than one thread concurrently. This situation may change the final result of the shared object after the execution gets finished.
          
There synchronization comes into picture it will prohibits the sharing of a common object by multiple thread concurrently.


class share
{
          synchronized void show(String s)
          {
                   System.out.print("["+s);
                   try
                   {
                             Thread.sleep(1000);
                   }catch(InterruptedException e)
                   {
                            
                   }
                   System.out.println("]");
          }
}
class cls extends Thread
{
          String name;
          share shh;
          cls(share sh,String s)
          {
                   shh=sh;
                   name=s;
                   start();
          }
          public void run()
          {
                   shh.show(name);
          }
}
public class xyz
{
          public static void main(String as[])
          {
                   share s=new share();
                   cls c1=new cls(s,"one");
                   cls c2=new cls(s,"two");
                   cls c3=new cls(s,"three");
                   try
                   {
                             c1.join();
                             c2.join();
                             c3.join();
                   }
                   catch(InterruptedException e)
                   {
                            
                   }
                   System.out.println("main thread gets finished");
          }
}


No comments:

Post a Comment