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

| Course Home | Prev Lect | Next Lect | Example Progs | Exercise Solns | CoreJava Progs Documentation |
Gen'l Docs | Java 2 APIs | Java Glossary | Term Proj Info |
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.
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.
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.