Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

///[Thread]///

 
chao-long liao
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marcus Green mock exam....
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 "vandeleur" but possible output of "vandeleur 0 1 2 3"
The answer is 4,and here is the explain,If that seems a vauge answer it is because you cannot be certain of the system that the underlying OS uses for allocating cycles for a Thread. The chances are that once the thread has been spun off in the call to start in the method piggy the main method will run to completion and the value of sName will still be vandeluer before the Thread modifies it. You cannot be certain of this though.
I can't understand what it say,somebody help me please.
 
Amir Ghahrai
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought the answer should always be the same regardless of the underlying OS.
String objects are immutable.
Even though you call the piggy method,
the change is local to the method but the original String object sName doesn't change.
so it should always return the string vandeleur.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The run method creates new string objects and assign them to the field sName. Thus if the run method is executed before the println statement, the output is not going to be vandeleur only.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic