-2

I have one question regarding the post Synchronized block not working, the following code is printing “Hello Java” …. 20 times for obj1 and obj2. This code is similar to that one given in the post.

As per the explanation, shouldn't the following code also have varying output? Can someone please help me to understand the difference between the two?

class ThreadDemo implements Runnable 
{ 
    String x, y; 
    public void run() 
    { 
        for(int i = 0; i < 10; i++) 
            synchronized(this) 
            { 
                x = "Hello"; 
                y = "Java"; 
              System.out.print(x + " " + y + " ");
            } 
    }

    public static void main(String args[]) 
    { 
        ThreadDemo run = new ThreadDemo (); 
        Thread obj1 = new Thread(run); 
        Thread obj2 = new Thread(run); 
        obj1.start(); 
        obj2.start(); 
    } 
}
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Ankita
  • 27
  • 3

2 Answers2

2

You are printing only x and y which are in synchronized block so it's printing the same value. Add i which is the outside synchronized block ,in print and you would see varying output.

class ThreadDemo implements Runnable 
{ 
    String x, y; 
    public void run() 
    {
        for(int i = 0; i < 10; i++) 
            synchronized(this)
            {
                x = "Hello";
                y = "Java";
              System.out.println(x + " " + y + " "+i);
            }
    }
    public static void main(String args[]) 
    { 
         ThreadDemo run = new ThreadDemo (); 
        Thread obj1 = new Thread(run); 
        Thread obj2 = new Thread(run); 
        obj1.start(); 
        obj2.start(); 
    } 
}
Vikas
  • 6,868
  • 4
  • 27
  • 41
0

You're obtaining a lock on the instance of ThreadDemo on which that run() method is being called. Since both threads are using the same object the Synchronized block is working here.

Arun Kumar
  • 16
  • 1