This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
piggy() will return faster than thread will be constructed after start() and thus will print current value of sName. sName in the piggy() is local to that method since parameter passed in is with the same name. In order to get "wiggy" added "this" should be used (this.sName = this.sName + sName).
Joined: Oct 29, 2002
In which condition will these codes output "vandeleur"?In which condition wil these codes output "vandeleur 0 1 2 3"?
It depends on the thread scheduler. Once start() is called within piggy(), a new thread is started - now it's a race between the new thread and the original one to see what happens next. If the original thread executes
before the new thread executes
then vandeleur is printed; otherwise you may see vandeleur 1 or vandeleur 1 2 or vandeleur 1 2 3 depending on how many times the new thread executes the loop before the print statement is executed. It's impossible to guarantee what will happen here.
"vandeleur" will be the only output ever. 1. Start() returns immediately so the print statement will occur before the thread even gets started. This is all but guaranteed. 2. Wiggy is only ever found inside of the local variable in the piggy method. it will never affect the static variable of the same name.
Joined: Jan 30, 2000
This is all but guaranteed. True - all but. Perhaps it is indeed always true on current JVMs, but it's not specified anywhere as far as I know. It would be perfectly possible for someone to make a JVM which immediately yields to a thread that has just been started, I think. As such I believe the original answer is best: probably output of "vandeleur" but possibly output of "vandeleur 0 1 2 3". [ November 06, 2002: Message edited by: Jim Yingst ]