Synchronization in Java


Access through single resource by multiple threads is called Synchronization. In this program we make a simple class of sync which is extending threads and there is one static string message on which we can apply synchronization.

Source Code 


classSync extends Thread
{
                static String msg[]={"Helo", "There", "is ", "AN", "Developer", "LEP"};

                Sync(String thread)

                {

                                                super(thread);

                }

                public void run()

                {

                                                Display(getName());

                }

                public synchronized voidDisplay(String thread)

                {

                                for(inti=0;i<=4;i++)

                                                                System.out.println(thread+msg[i]);

                                try

                                {

                                                                this.sleep(10000);

                                }

                                catch(Exception e)

                                {

                                }

                }

}

publicclasssynchronization 
{

                public static void main(String[] argss)

                {

                                                Sync S1=newSync("First Thread : ");

                                                S1.start();

                                                Sync S2=newSync("Second Thread : ");

                                                S2.start();
                                               
                }

}

Output of the Program 


Synchronization in java
Synchronization in java


Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment