Chapter 20. Multithreading

CHAPTER GOALS

  • To understand how multiple threads can execute in parallel

  • To learn how to implement threads

  • To understand race conditions and deadlocks

  • To avoid corruption of shared objects by using locks and conditions

  • To be able to use threads for programming animations

It is often useful for a program to carry out two or more tasks at the same time. For example, a web browser can load multiple images on a web page at the same time. Or an animation program can show moving figures, with separate tasks computing the positions of each separate figure.

In this chapter, you will see how you can implement this behavior by running tasks in multiple threads, and how you can ensure that the tasks access shared data in a controlled fashion.

Running Threads

Note

A thread is a program unit that is executed concurrently with other parts of the program.

A thread is a program unit that is executed independently of other parts of the program. The Java virtual machine executes each thread for a short amount of time and then switches to another thread. This gives the illusion of executing the threads in parallel to each other. Actually, if a computer has multiple central processing units (CPUs), then some of the threads can run in parallel, one on each processor.

Running a thread is simple in Java—follow these steps:

  1. Implement a class that implements the Runnable interface. That interface has a single method called run:

    public interface Runnable
    {
       void run();
    }
  2. Place the code for your ...

Get Big Java, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.