• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread Question

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
The City calls upon her steadfast protectors. Now for a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic