Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is run() not immediately called when start() called on a thread object in java

Or is it?
I have a thread object from:

Thread myThread = new Thread(pObject);

Where pObject is an object of a class implementing the Runnable interface and then I have the start method called on the thread object like so:

myThread.start();

Now, my understanding is that when start() is called, the JVM implicitly (and immediately) calls the run() method which may be overridden (as it is in my case)

However, in my case, it appears that the start() method is not called immediately (as desired) but until the other statements/methods are completed from the calling block i.e. if I had a method after the start() call like so:

myThread.start();
doSomethingElse();

doSomthingElse() gets executed before the run() method is run at all.
Perhaps I am wrong with the initial premise that run() is always called right after the start() is called. Please help! The desired again is making executing run() right after start(). Thanks.

like image 685
pi. Avatar asked Apr 22 '10 11:04

pi.


2 Answers

Um... the run() method will run in a different thread. That, per definition, means you cannot make any assumptions about before or after which statements in the current thread it will execute, unless you synchronize them explicitly.

like image 133
Michael Borgwardt Avatar answered Oct 10 '22 02:10

Michael Borgwardt


run() is the first thing within your code that the new thread does, but there's some set-up work that the new thread does first, and there's no guarantee that any significant amount of work will by done by the new thread before the original thread goes on to call doSomethingElse().

You're right in thinking that there are no guarantees here. Making assumptions about the behaviour of multithreaded code is the source of much pain - try not to do it!

like image 26
RichieHindle Avatar answered Oct 10 '22 04:10

RichieHindle