• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
ganesh subbiah
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the output will uncertain
 
ganesh subbiah
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx but how ?? explain theoratically or give the suggested output?
 
ganesh subbiah
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic