It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes about thread.start() and 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 "about thread.start() and" Watch "about thread.start() and" New topic

about thread.start() and

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
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

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 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
I agree. Here's the link:
subject: about thread.start() and
It's not a secret anymore!