Saturday, 10 June 2017

Java Tutorial: Java Synchronization (Synchronization in java | Java Synchronized method in java_V3) ~ foundjava


Click here to watch in Youtube :
https://www.youtube.com/watch?v=upMx004iX1A&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial: Java Synchronization (Synchronization in java | Java Synchronized method in java_V3) 
DisplayMessage.java
public class DisplayMessage
{

    /*
     *  Method is synchronized
     */
    public synchronized void showMessage(String msg)
    {
        System.out.println("Thread Name = "
                    + Thread.currentThread().getName());
        System.out.print("[" + msg);
        try
        {
            Thread.sleep(1000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        System.out.println("]");
    }

}
DisplayThread.java
public class DisplayThread extends Thread
{
    private String msg;
    private DisplayMessage displayMessage;

    public DisplayThread(DisplayMessage displayMessage, String msg)
    {
        this.displayMessage = displayMessage;
        this.msg = msg;
    }

    public void run()
    {
        displayMessage.showMessage(msg);
    }
}
SynchronizationDemo.java
public class SynchronizationDemo
{
    public static void main(String[] args)
    {
        DisplayMessage displayMessage = new DisplayMessage();
        DisplayThread thread1 = new DisplayThread(displayMessage, "welcome");
        DisplayThread thread2 = new DisplayThread(displayMessage, "Hello");
        DisplayThread thread3 = new DisplayThread(displayMessage, "Peter");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
Output
-------------------------------------
If showMessage method is synchronized,
then below will be the output:
-------------------------------------

Thread Name = Thread-0
[welcome]
Thread Name = Thread-2
[Peter]
Thread Name = Thread-1
[Hello]

-----------------------------------------
If showMessage method is not synchronized, 
then below will be the output:
-----------------------------------------

Thread Name = Thread-0
[welcomeThread Name = Thread-2
Thread Name = Thread-1
[Hello[Peter]
]
]
Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment