CISC 370 Lecture Notes for Class No. 25 May 9, 2000
Java Threads

Course Home Prev Lect Next Lect Example Progs Exercise Solns
CoreJava Progs
Documentation
Gen'l Docs Java 2 APIs Java Glossary Term Proj Info

Assignment

Reading:
Horstmann & Cornell, Vol II, chapter 1 on Multithreading or the online chapter on threads from the Java Tutorial by Campione and Walrath.

Extra Credit Exercise: Augment version 2 of the vacation program by adding a third thread with Delaware as the destination.

Today's Lecture Topics

  1. Threads (aka Light Weight Processes)

    What is a thread? A thread is a single sequential flow of control within a program. In a Java program it is possible to have many different threads all appearing to "run at the same time" in parallel and performing different tasks.

    Threads can either run in an independent asynchronous fashion (the simplest way) or they may interact with each (for example, by sharing some data) and must be synchronized. Synchronized threads require much more programming care. We begin with a couple of asynchronous examples.

  2. The vacation chooser. This is an example of two threads that "race" to see which gets to its vacation destination first. Each thread has 10 legs of the trip to complete and prints out a number 0 to 9 as each leg is completed.

    There are two methods for setting up a thread: (1) subclassing the java.lang.Thread class and overriding its run() method or (2) implementing the java.lang.Runnable interface. A reference to an object of the class that implements Runnable must be passed to the Thread constructor when the thread is created so that the thread will know where to find its run() method. Vacation chooser, version 1 , is implemented by subclassing the Thread class.

    Vacation chooser, version 2 , is implemented via the Runnable interface.

    If your class must subclass another class, like Applet, then it cannot also subclass the Thread class and you are forced to use the second method. Otherwise, the first method is usually a bit simpler.

  3. The synchronized traffic and pedestrian lights

A nice example of using threads to implement a clock .

Back to the CISC 370 homepage.

Last updated 18 July 2000.

Corrections, suggestions and comments to Bob Caviness

Copyright 2000 B. F. Caviness This page has been accessed times since 9 May 2000.