• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

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
 
What is that? Is that a mongol hoarde? Can we fend them off with this tiny ad?
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic