O'Reilly logo

Java in a Nutshell, 5th Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); } // ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required