This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes about thread.start() and thread.run() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "about thread.start() and thread.run()" Watch "about thread.start() and thread.run()" New topic
Author

about thread.start() and thread.run()

ganesh subbiah
Ranch Hand

Joined: Nov 18, 2004
Posts: 39
In Reference to this mock green's question explain Thread class start()
and run() methods
Which statement is true of the following code?

1) Compile time error, class Rpcraven does not import java.lang.Thread
2) Output of One One Two Two
3) Output of One Two One Two
4) Compilation but no output at runtime

if the run() method is replaced by start() method what will be the output?


(please use tags and format your code)
[ December 20, 2004: Message edited by: Barry Gaunt ]
dx wu
Ranch Hand

Joined: Apr 28, 2002
Posts: 60
the output will uncertain


good good study , day day up!
ganesh subbiah
Ranch Hand

Joined: Nov 18, 2004
Posts: 39
thanx but how ?? explain theoratically or give the suggested output?
ganesh subbiah
Ranch Hand

Joined: Nov 18, 2004
Posts: 39
I compiled the code but got Exception in thread "main" java.lang.ClassFormatError: Pmcraven (Truncated class
file)
when I removed yield() it gave output as:
one one two two

with start it gave
one two one two

explain the differences
thanx in advance
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

The code compiles and runs fine for me.

A direct call to run() will execute the method in the current thread, rather than in its own thread. So pm1.run() must return before pm2 is even created -- which is why the output is One, One, Two, Two.

But if we use start() instead of run(), then the thread will be put in a ready state, eligible for execution. So pm1.start() puts pm1 in a ready state, and pm2.start() puts pm2 in a ready state. At that point, they are separate threads, at the mercy of the platform-dependent scheduler. However, given the sleep and yield commands, it's a fairly "reasonable" expectation that these threads will alternate their execution and output One, Two, One, Two.


[ December 20, 2004: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: about thread.start() and thread.run()