aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Question" Watch "Thread Question" New topic
Author

Thread Question

Kayalvizhi Umashankar
Greenhorn

Joined: Aug 04, 2005
Posts: 25
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

Joined: Feb 04, 2002
Posts: 22
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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Thread Question