How Tomcat Works
A Guide to Developing Your Own Java Servlet Container
Catalina uses many threads to handle different things. This chapter's application assigns a separate thread for handling requests. Therefore, you need to understand how to work with threads in Java, as described in this section.
There are a number of ways to create a new thread of execution. One is to declare a class to be a subclass of java.lang.Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started. For example, consider the test.ThreadDemo class in Listing 3.1.
Listing 3.1: The ThreadDemo Class
package test;
public class ThreadDemo extends Thread {
public void run() {
int counter = 0;
while (counter < 5) {
System.out.println("running " + counter);
counter++;
}
}
public static void main(String[] args) {
ThreadDemo demo = new ThreadDemo();
demo.start();
}
}
The ThreadDemo class extends java.lang.Thread and overrides the Thread class’s run method. The run method is executed when the Thread is started by calling its start method. In the ThreadDemo class, the main method creates a Thread and starts it, which results in the run method being executed. When the ThreadDemo class is run, the following output is displayed in the console.
running 0running 1running 2running 3running 4
The ThreadDemo class uses inheritance. However, if you are only interested in overriding the run method of the Thread, you are better off implementing the java.lang.Runnable interface and providing the implementation of the interface’s run method, and this is the second way to create a thread. An instance of your class can then be allocated, passed as an argument when creating Thread, and started. The test.RunnableDemo class in Listing 3.2 does the same thing as the ThreadDemo class.
Listing 3.2: The RunnableDemo Class
package test;
public class RunnableDemo implements Runnable {
public void run() {
int counter = 0;
while (counter < 5) {
System.out.println("running " + counter);
counter++;
}
}
public void start() {
Thread thread = new Thread(this);
thread.start();
}
public static void main(String[] args) {
RunnableDemo demo = new RunnableDemo();
demo.start();
}
}
The technique used to create a thread by implementing the Runnable interface is used for the ex03.pyrmont.connector.http.HttpConnector class, as you will see later in this chapter.