Threads and Concurrent Programming

Threads may be seen as methods that execute at "the same time" as other methods. Normally, we think sequentially when writing a computer program. From this perspective, only one thing executes at a time. However, with today's multi-core processors, it is possible to literally have several things going on at the very same time while sharing the same memory. There are lots of ways that this is done in the real world, and this chapter goes over them in a way that you can apply to your own projects.

14.3 From the Java Library: java.

The java.lang.Thread class contains the public methods shown in Figure 14.4 (the figure contains only a partial list). Note that Thread implements the Runnable interface, which consists simply of the run() method. As we will now see, another way to create a thread is to instantiate a Thread object and pass it a Runnable object that will become its body. This approach allows you to turn an existing class into a separate thread.

Annotation 2020-03-24 205549A Runnable object is any object that implements the Runnable interface—that is, any object that implements the run() method (Fig. 14.5). The following example provides an alternative way to implement the NumberThread program:

Annotation 2020-03-24 205659

Given this definition, we would then pass instances of this class to the individual threads as we create them:

Annotation 2020-03-24 205817

The NumberPrinter class implements Runnable by defining exactly the same run() that was used previously in the NumberThread class. We then pass instances of NumberPrinter when we create the individual threads. Doing things this way gives exactly the same output as earlier. This example serves to illustrate another way of creating a multithreaded program: 

  • Implement the Runnable interface for an existing class by implementing the void run() method, which contains the statements to be executed by that thread. 
  • Create several Thread instances by first creating instances of the Runnable class and passing each instance as an argument to the Thread() constructor. 
  • For each thread instance, start it by invoking the start() method on it.

Annotation 2020-03-24 210018

Annotation 2020-03-24 210107


SELF-STUDY EXERCISE 

EXERCISE 14.1 Use the Runnable interface to convert the following class into a thread. You want the thread to print all the odd numbers up to its bound:

Annotation 2020-03-24 210234