• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Question

 
Kayalvizhi Umashankar
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A9o extends Thread
{
String[] sa;
public A9o(String[] sa) {this.sa = sa;}
public void run()
{
synchronized (sa)
{
System.out.print(sa[0] + sa[1] + sa[2]);
}
}
}

class TestCalss5
{
private static String[] sa = new String[]{"X","Y","Z"};
public static void main (String[] args)
{
synchronized (sa)
{
A9o t1 = new A9o(sa); t1.start();
try{t1.join(900);} catch(InterruptedException e){}
sa[0] = "A"; sa[1] = "B"; sa[2] = "C";
}
}
}

In the above code, when the either of the synchronized statements are removed then the output is "XYZ" orelse "ABC".

Please explain.

Thanks in advance

Kayal
 
Nandu Jawale
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

It is because both threads (main and t1) are synchronized on same reference.
Thread t1 will not be in "running" state unless main thread comes out of
synchronized block. And by that time it has modified the contents of string array.

If you remove any of synchronized block, 900 milliseconds are sufficient
(although it is not a guarantee) to t1 to run. So you may not always get
"XYZ" in that case.

Hope this helps.
Nandu
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic