Wednesday, 8 February 2017

Java Tutorial: Java Synchronization (Synchronization in java | synchronized block in java_V3)


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

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

    public void showMessage(String msg)
    {

        /*
         * synchronized block.
         */
        synchronized (this)
        {
            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 has synchronized block,
then below will be the output:
-------------------------------------

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

-----------------------------------------
If showMessage method does not have synchronized block,
then below will be the output:
-----------------------------------------
Thread Name = Thread-0
Thread Name = Thread-1
Thread Name = Thread-2
[Hello[welcome[Peter]
]
]
Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/Synchronization_Block_Demo_V3_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/Synchronization_Block_Demo_V3_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/644abf74fceeb240066dd3d2fe2e4b1fb6c4bd48/BasicJava/Synchronization_Block_Demo_V3_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment