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

Marcus Green #3 Q19 (Thread question)

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
The question states:
What will happend when you attempt to compile and run the following code?
public class Tux extends Thread{
static String sName = "vandeleur";
public static void main(String argv[]){
Tux t = new Tux();
t.piggy(sName);
System.out.println(sName);
}
public void piggy(String sName){
sName = sName + " wiggy";
start();
}
public void run(){
for(int i=0;i < 4; i++){
sName = sName + " " + i;
}
}
}
1) Compile time error
2) Compilation and output of "vandeleur wiggy"
3) Compilation and output of "vandeleur wiggy 0 1 2 3"
4) Compilation and probably output of "vandelur" but possible output of "vandeleur 0 1 2 3"
The answer says:
4) Compilation and probably output of "vandelur" but possible output of "vandeleur 0 1 2 3"
Why is the answer POSSIBLE output of "vandeleur 0 1 2 3" ? I was sure that this was ALWAYS in the
output, because the thread is NOT a daemon thread...
 
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
The program has no synchronization, therefore you cannot predict whether run() will run before or after the System.out.println(sName); at the end of main().
It's even possible (though less likely) that you could get one of the following outputs:
vandeleur 0 1 2
vandeleur 0 1
vandeleur 0
So I don't think this question is in error.
[ August 20, 2002: Message edited by: Ron Newman ]
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
Please do not post the same question in multiple forums.
Continue this discussion at https://coderanch.com/t/238952/java-programmer-SCJP/certification/Marcus-Green-Thread
 
Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic