Chapter 2. The Java ThreadingAPI

In this chapter, we will create our own threads. As we shall see, Java threads are easy to use and well integrated with the Java environment.

Threading Using the Thread Class

In the last chapter, we considered threads as separate tasks that execute in parallel. These tasks are simply code executed by the thread, and this code is actually part of our program. The code may download an image from the server or may play an audio file on the speakers or any other task; because it is code, it can be executed by our original thread. To introduce the parallelism we desire, we must create a new thread and arrange for the new thread to execute the appropriate code.

Let’s start by looking at the execution of a single thread in the following example:

public class OurClass {
    public void run() {
        for (int I = 0; I < 100; I++) {

In this example, we have a class called OurClass. The OurClass class has a single public method called run() that simply writes a string 100 times to the Java console or to the standard output. If we execute this code from an applet as shown here, it runs in the applet’s thread:

import java.applet.Applet;

public class OurApplet extends Applet {
    public void init() {
        OurClass oc = new OurClass();;

If we instantiate an OurClass object and call its run() method, nothing unusual happens. An object is created, its run() method is called, and the “Hello” message prints 100 times. Just like other method ...

Get Java Threads, Second Edition now with the O’Reilly learning platform.

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