Threads and Concurrency

The Java platform has supported multithreaded or concurrent programming with the Thread class and Runnable interface since Java 1.0. Java 5.0 bolsters that support with a comprehensive set of new utilities for concurrent programming.

Creating, Running, and Manipulating Threads

Java makes it easy to define and work with multiple threads of execution within a program. java.lang.Thread is the fundamental thread class in the Java API. There are two ways to define a thread. One is to subclass Thread, override the run( ) method and then instantiate your Thread subclass. The other is to define a class that implements the Runnable method (i.e., define a run() method) and then pass an instance of this Runnable object to the Thread() constructor. In either case, the result is a Thread object, where the run() method is the body of the thread. When you call the start() method of the Thread object, the interpreter creates a new thread to execute the run() method. This new thread continues to run until the run( ) method exits. Meanwhile, the original thread continues running itself, starting with the statement following the start() method. The following code demonstrates:

final List list; // Some long unsorted list of objects; initialized elsewhere /** A Thread class for sorting a List in the background */ class BackgroundSorter extends Thread { List l; public BackgroundSorter(List l) { this.l = l; } // Constructor public void run() { Collections.sort(l); } // ...

Get Java in a Nutshell, 5th 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.