Previous | Next | Trail Map | Writing Java Programs | Table of Contents


Threads of Control

Below is three copies of an applet that animates different sorting algorithms. No, this lesson is not about sorting algorithms. But these applets do provide a visual aid to understanding a powerful capability of the Java language--threads.
                  Bi-Directional
Bubble Sort        Bubble Sort      Quick Sort
          
Now start each of the applets, one by one, by clicking on them with the mouse. Notice anything? Yes! The applets are running side by side at the same time! Notice anything else? Yes! You can also scroll this page or bring up one of your browser's panels at the same time that the three sorting applets sort their data. All of this is due to the power of threads.

What Are Threads?

A thread--sometimes known as an execution context or a lightweight process--is a single sequential flow of control within a process.

A Simple Thread Example

The following program is a simple Java application that creates and starts two independent threads.
class TwoThreadsTest {
    public static void main (String args[]) {
        new SimpleThread("Jamaica").start();
        new SimpleThread("Fiji").start();
    }
}
class SimpleThread extends Thread {
    public SimpleThread(String str) {
	super(str);
    }
    public void run() {
	for (int i = 0; i < 10; i++) {
	    System.out.println(i + " " + getName());
            try {
		sleep((int)(Math.random() * 1000));
	    } catch (InterruptedException e) {}
	}
	System.out.println("DONE! " + getName());
    }
}

Thread Attributes

To use threads efficiently and without errors you must understand various aspects of threads and the Java runtime system. You need to know how to provide a body for a thread, the life-cycle of a thread, how the runtime system schedules threads, thread groups, and what daemon threads are and how to write them.

Mulithreaded Programs

Up until now all of the sample programs in this lesson have used either one thread or multiple independent threads that run asynchronously. However, it is often useful to use multiple threads that share data and therefore must run synchronously. Typically, programs that use multiple synchronous threads are called multithreaded programs and require special handling.

Summary

This lesson has taken you through the intricacies of Java threads including the life-cycle of a Java thread, scheduling, thread groups, and synchronization. The Java development environment supports multithreaded programs through the language, the libraries, and the runtime system. This summary page highlights all of the features in the Java development environment that supports threads and gives you links to further documentation about those features.


Previous | Next | Trail Map | Writing Java Programs | Table of Contents