File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes MG1 #54 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "MG1 #54" Watch "MG1 #54" New topic
Author

MG1 #54

Vicken Karaoghlanian
Ranch Hand

Joined: Jul 21, 2003
Posts: 522
can someone explain the following code (preferably in steps)?

the output is one one two two


- Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth. <br />- What truth? <br />- That there is no spoon!!!
Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
Please note that this code is not 'starting' new threads as it might appear to be. To start a thread you need to issue:
obj.start()
but this code is saying:
obj.run()
Therefore run() method is called as regular method. No new thread is created. After first run() call is returned, second is run() is executed.
Hope this makes sense.
Barkat
Vicken Karaoghlanian
Ranch Hand

Joined: Jul 21, 2003
Posts: 522
i totally agree that there is no threads being started, however i am a bit confused about sleep followed by yields. can you please clarify?
Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
Each call for run() will sleep for a second and then attempt to yield. But as you said there is not other thread to yield to, same thread (main) will continue.
Hope this makes sense.
Barkat
shirley tao
Greenhorn

Joined: Sep 07, 2003
Posts: 12
But if we change the "run" to "start", what's the difference of the result?
and what's the use of the yield in the code?
Thanks!
Shirley
Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
posted by Shirly:
But if we change the "run" to "start", what's the difference of the result?
and what's the use of the yield in the code?
Thanks!
Shirley

The output will be unpredictable. yield is used to allow other methods of same priority to run.
Vicken Karaoghlanian
Ranch Hand

Joined: Jul 21, 2003
Posts: 522
Originally posted by Barkat Mardhani:
posted by Shirly:

The output will be unpredictable. yield is used to allow other methods of same priority to run.

yield is used to allow other methods of same or higher priority to run.
[ September 18, 2003: Message edited by: Vicken Karaoghlanian ]
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
There is no gaurantee whether the thread which is allowed to run is of more, less or equal priority.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: MG1 #54