16.1. Starting Threads

The Java implementation provides two convenient mechanisms for thread programming: (1) making a separate subclass of the Thread class that contains the code that will be run, and (2) using a Thread instance to call back to code in an ordinary object.

Mechanism 1: Put Behavior in a Separate Thread Object

The first way to run threads in the Java platform is to make a separate subclass of Thread, put the actions to be performed in the run method of the subclass, create an instance of the subclass, and call that instance's start method. This technique is illustrated in Listings 16.1 and 16.2.

Listing 16.1. DriverClass.java
 public class DriverClass extends SomeClass { ... public void startAThread() { // Create a Thread object. ...

Get Core Web Programming, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.