hi frnds, my name is kannan and i have a doubt which is bugging me for a long time - hope i get an ans here in this discussion group. i have read umpteen number of times that a thread should be run only through the start() method but no one has come out clearly as to y ?? my question is y should a thread be run only using the start method, cant we call the run method directly ?? whats so special about this start method and why is run() dependent upon start ?? thanking you in advance kannan
Hi, Welcome to JavaRanch! If you call run() directly, then the code in run() will execute in the calling thread, and the calling thread can't continue until run() completes. If you call start(), then magic code deep inside the JVM will create an actual separate thread and call run() from it, while the start() returns and the original thread keeps going, so that now two methods are executing simultaneously. This is the whole point of the Thread class. OK?
Hi Mr.Friedman, thank you very much for your inputs on this query of mine. infact i was posted this question in an interview and i was unable to give a genuine explanation, so i had to post this question in this discussion group. thank you once again kannan
Their is nothing really wrong with calling the run method, it will behave just as any other method. The start method is a special method. Its the one that actually creates and 'starts' a new thread of execution, after which the method run will be called by this new thread.
Not only for the above reasons, but this also: In the life cycle of a thread, especially if you are dealing with multiple threads (like 3 or 4 ), Java handles these threads based on the states they are in. For example, ONLY after start() is called is a thread in the 'ready' state - and ONLY threads in the 'ready' state are in line for processor time. Once there is available processor time, the next 'ready' thread in line with the highest priority is allowed to execute its run() method, which puts that thread in a 'running' state. If this thread is interrupted for a higher priority thread, then it is told to wait(), and it is again put in the 'ready' state, which puts it back in line for processor time. I don't know WHO handles all of this, I just know this is HOW its handled. It would be interesting to know, however, if threads that have their run() method called directly actually run to completion regardless, or if they can be interrupted and put back in a ready state anyway. I'll have to write a tester program for that...maybe I'll post it.
-nothing important to say, but learnin' plenty-
My name is Inigo Montoya, you killed my father, prepare to read a tiny ad: