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.
That is incorrect. It does implicitly call
run(), but the call does not necessarily happen immediately.The reality is that the new thread becomes available to be scheduled at some point in time after the
start()call is made. The actual scheduling is up to the native scheduler. It could happen immediately, or the parent thread could continue for a period before the child thread is scheduled.To force your thread to start running immediately (or to be more accurate, to start running before
doSomethingElse()), you need to do some explicit synchronization; e.g. something like this:where
There are other ways to implement the synchronization using the concurrency classes, or Java’s mutex / wait / notify primitives1. But explicit synchronization between the two threads is the only way to guarantee the behavior that you require.
Note that the
doSomething()call in the child thread will complete before the parent thread is released, but we can say nothing about the order of execution ofdoSomethingElese()anddoSomeMoreStuff(). (One might run before the other and vice versa, or they might run in parallel.)1 – Using
wait/notifyis not recommended, but it may be your only option if the concurrency APIs are not available; e.g. on Java ME.