-Threads -

Producers, Consumers and Observers


Thread "issues" have already been mentioned when we discussed the loading of images. MediaTracker() provides the necessary synchronization between our applet Thread and one started in the API to actually load the image. In this example, this second Thread can be observed by using the static method currentThread() which returns information about the Thread that is executing when the method is called.

One can get a glimpse of what is going on by looking at the following, admittedly contrived, example.
The idea is to calculate the product of two numbers between 0 and 9 using a two-Threaded program.


Note:

  1. How Threads are created and started using start() - run()

  2. The dual role of the consumer as the object that actually uses the table and as "observer" of the progress of the producer, as measured by Table_update().

  3. It is worth repeating that it is the producer Thread that does the actual calculation by invoking this method on the consumer Object.

. The above examples hint at new approaches to program design that Threads make possible. This subject alone could occupy much of a semester course. Those who are interested in persuing this material in depth might wish to look at

Multithreaded Programming with Java Technology
      by Lewis and Berg Prentice-Hall

To briefly introduce this subject, one notes that, in programming with Threads one needs to consider that

Consideration of these issues quickly leads to the conclusion that one needs more sophisticated methods of synchronization than were used in the above examples. Here is a simple example, using join().
 
Here is an example of a Thread that demonstrates more sophisticated synchronization between threads using
wait() -notify().

Exercise: Use these methods to develop a new class TableTracker that acts like MediaTracker, but for multiplication tables rather than images.