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();
}
}