Page 828 - Introduction to Programming with Java: A Problem Solving Approach
P. 828
794 Chapter 15 Files
APPENDIX 9
Multithreading
To understand this appendix, you need to be familiar with object-oriented programming, inheritance, ex- ception handling, and files. As such, you need to have read up through Chapter 15.
This appendix introduces a feature, multithreading, that helps Java programs take advantage of the parallel processing capabilities contained in many modern computers. By taking advantage of parallel pro- cessing capabilities, multithreading can lead to faster programs. And that in turn leads to more user-friendly programs.
Threads
A thread is a “lightweight process.”1 Think of it as a coherent code fragment. Ideally, once it has a certain minimum amount of initial information, a thread can run all the way to completion without any more infor- mation from the outside world. IdAeapllya, dgiffeorent tPhrDeadFs areEinndephenadent.cer
A thread is an object derived from a class that extends the predefined Thread class, and you must
override the Thread class’s run method to specify what you want your thread to do. You can call an
object’srunmethodonlyonce,andyoumustdoitindirectlybycallingthepublic void start()
method, which your class inherits from the Thread class. The start method asks the JVM to call your
2
starting one thread, your software could start another thread, and you would have three chunks of code run- ning in parallel. You could continue like this to obtain as many parallel operations as you might want. Your computer automatically takes advantage of these relatively independent chunks of code to keep its various parallel hardware components as busy as possible. The driver in Figure A9.1 shows how easy it is to launch new threads.
1 A “lightweight process” has its own “program counter” and its own “stack,” but otherwise it has normal access to the rest of the program in which it exists. A thread’s program counter keeps track of where the execution is, and the stack remembers how to return from function calls. Whenever a thread temporarily stops, the computer takes a snapshot of that thread’s program counter and stack, and this enables the execution to re-start exactly where it left off when the thread starts running again.
2 If your class already implements some other class, you can make it work like a thread by also implementing the Runnable in- terface. To start the run method of a class that implements Runnable but does not extend Thread, your class should also include a start method that does this:
public void start()
run method.
This operation makes the newly started thread run in parallel with the software that called it. After thus
{
}
new Thread(this).start();
For simplicity, we restrict our discussion to classes that implement the Thread class. 794