. .
If you created a thread using a Runnable, the Runnable is reusable. Indeed, if you did not
specify any instance variables in the Runnable, you could simply create a single runnable object
and create lots of threads that all used it. On the other hand, if you think you might change your
program someday, or if someone else might end up maintaining it, this could be awkward. In all
our programs we create a new Runnable for every thread.
An Example: Create and Join
In Figure 4-4 we show the operation of the program, which makes a series of calls
to create threads, stop them, and join them. The basic code is very simple and should require little
explanation. A series of well-placed calls to sleep() arranges for the threads to execute in
exactly the order we desire. Removing those calls (or setting breakpoints in the debugger) will
cause the speed and order of execution to change, and some things will not work as intended. The
program is not correct, per se, but it is a useful illustration of how to create and join threads
without all that unsightly synchronization code.
The Main Thread Is Different
One slightly unusual aspect of this program is that we create a new thread which we call
threadMain (Code Example 4-9, which follows). The actual main thread is identical to all the
other threads, except for one thing. Because you did not create it, you do not know whether or not
main() corresponds exactly to run(). In particular, just because main() returns does not imply
that the main thread can then be joined.
Example 4-9 Java Create and Join
Simple program that just illustrates thread creation, thread
exiting, waiting for threads, and interrupting threads.
This program relies completely on the accuracy of the sleep()
method, something that is ill advised in a real program.
For this example, that's OK. When you write programs,
don't do that!
import Extensions.*;
public class Multi {
static Thread
threadA, threadB, threadC;
static Thread
threadD, threadE, threadMain;
public static void main(String[] args) throws Exception {
threadMain = new Thread(new MyMain(), "threadMain");
class MyMain implements Runnable {
static long startTime = 0;
public void run()  {
startTime = System.currentTimeMillis();
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks