| ||||
Copyright 1999 Sams Publishing |
|
Spawning a New Thread |
New threads are spawned from threads that are already running. First, a new Thread instance must be constructed . In this example, a new TwoThread object will work just fine because TwoThread IS-A Thread : |
TwoThread tt = new TwoThread(); |
The next step is to kick off the execution of the thread by invoking the start() method on the TwoThread object ( start() is inherited from Thread ): |
tt.start(); |
A call to start() returns right away and does not wait for the other thread to begin execution. In start() , the parent thread asynchronously signals through the JavaVM that the other thread should be started as soon as its convenient for the thread scheduler. At some unpredictable time in the very near future, the other thread will come alive and invoke the run() method of the Thread object (or in this case, the overridden run() method implemented in TwoThread ). Meanwhile, the original thread is free to continue executing the statements that follow the start() call. |
The two threads run concurrently and independently. On a multi-processor machine, these two threads may actually be running at the very same instant , each on its own processor. This true simultaneity would also have to be supported in the port of the JavaVM for that platform in order to exploit multiple processors. |
A more likely case is that only a single processor is present. The JavaVM and the operating system work together to schedule each thread for short, interleaved bursts of processor usage. Each thread takes a turn running while the other threads are frozen, waiting for their next turn on the processor. This context switching among threads generally occurs very quickly and gives the illusion of truly simultaneous execution. |
Caution | A newly created thread may start executing (enter the run() method) at any time after start() is invoked. This means that the original thread might be swapped out before any statement that follows start() is executed. |
If the original thread is executing this code |
stmt1(); |
tt.start(); |
stmt2 (); |
and the new thread has a run() method such as this |
public void run() { |
stmtA(); |
stmtB(); |
} | |
the order of actual statement execution in the processor might be stmt1() , tt.start() , stmt2() , stmtA() , and stmtB() . Alternatively, it might be stmt1() , tt.start() , stmtA() , stmtB() , and stmt2() . Perhaps, it might be one of the other permutations ! |
Important to note is that although the order in which each thread will execute its own statements is known and straightforward, the order in which the statements will actually be run on the processor is indeterminate, and no particular order should be counted on for program correctness. |
| |||
Toc |