Java Reference
In-Depth Information
Here is how the program works. The thread class MyThread defines two Boolean vari-
ables, suspended and stopped , which govern the suspension and termination of a thread.
Both are initialized to false by the constructor. The run( ) method contains a synchron-
ized statement block that checks suspended . If that variable is true , the wait( ) method is
invoked to suspend the execution of the thread. To suspend execution of the thread, call
mysuspend( ) , which sets suspended to true . To resume execution, call myresume( ) ,
which sets suspended to false and invokes notify( ) to restart the thread.
To stop the thread, call mystop( ) , which sets stopped to true . In addition, mystop( )
sets suspended to false and then calls notify( ) . These steps are necessary to stop a suspen-
ded thread.
Ask the Expert
Q :
Multithreading seems like a great way to improve the efficiency of my pro-
grams. Can you give me any tips on effectively using it?
A : The key to effectively utilizing multithreading is to think concurrently rather than
serially. For example, when you have two subsystems within a program that are fully
independent of each other, consider making them into individual threads. A word of
caution is in order, however. If you create too many threads, you can actually degrade
the performance of your program rather than enhance it. Remember, overhead is as-
sociated with context switching. If you create too many threads, more CPU time will
be spent changing contexts than in executing your program!
Try This 11-2 Using the Main Thread
All Java programs have at least one thread of execution, called the main thread , which is
given to the program automatically when it begins running. So far, we have been taking the
main thread for granted. In this project, you will see that the main thread can be handled
just like all other threads.
Search WWH ::




Custom Search