• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread Behaviour

 
Chandu Sree
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

I have checked the below code I got answer as "vandeleur".
but here in the mock test it is given as choice 4.
Can anyboby tell me which is correct answer..as i hav checked other papers they gav different answer..

What will happen 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 output of either "vandeleur", "vandeleur 0", "vandeleur 0 1" "vandaleur 0 1 2" or "vandaleur 0 1 2 3"



Thanks
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kindly UseCodeTags while posting code, it makes reading and understanding a bit easier.

The output of the program may be different for different runs.
The reference to the instance variable is passed to the newly created thread which changes its value.(re-assigns a new value)This newly created thread runs in parallel to the main thread so, the output of the program will depend on the execution of the thread.

In addition to the above, the line:

does not have an impact on the output because the variable sName is a local variable for the method piggy()

So, the output may be,
"vandeleur", "vandeleur 0", "vandeleur 0 1" "vandaleur 0 1 2" or "vandaleur 0 1 2 3"

You just got vandeleur because the new thread did not get into the loop when you printed the value of sName.
If you want to get different outputs you can try the below:

1) Add Thread.sleep() for a long time, before printing sName value. This will in most cases print vandaleur 0 1 2 3"
2) Add Thread.sleep() for a nano second or so, before printing sName value. You may get any of the mentioned output on different runs.

Sample code:


[ April 22, 2008: Message edited by: Nitesh Kant ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!