Java Reference
In-Depth Information
Thread Basics
Example 4-1 is a simple program that demonstrates how to define, manipulate,
and run threads. The bulk of the program is the main() method; it is run by the
initial thread created by the Java interpreter. This main() method defines two addi-
tional threads, sets their priorities, and starts them running. The two threads are
defined using two different techniques: the first is defined by subclassing the
Thread class, while the second implements the Runnable interface and passes a
Runnable object to the Thread() constructor. The example also demonstrates how
you might use the important sleep() , yield() , and join() methods. Finally,
Example 4-1 demonstrates the java.lang.ThreadLocal class, which has been
added as of Java 1.2.
Example 4−1: ThreadDemo.java
package com.davidflanagan.examples.thread;
/**
* This class demonstrates the use of threads. The main() method is the
* initial method invoked by the interpreter. It defines and starts two
* more threads and the three threads run at the same time. Note that this
* class extends Thread and overrides its run() method. That method provides
* the body of one of the threads started by the main() method
**/
public class ThreadDemo extends Thread {
/**
* This method overrides the run() method of Thread. It provides
* the body for this thread.
**/
public void run() { for(int i = 0; i < 5; i++) compute(); }
/**
* This main method creates and starts two threads in addition to the
* initial thread that the interpreter creates to invoke the main() method.
**/
public static void main(String[] args) {
// Create the first thread: an instance of this class. Its body is
// the run() method above
ThreadDemo thread1 = new ThreadDemo();
// Create the second thread by passing a Runnable object to the
// Thread() construtor. The body of this thread is the run() method
// of the anonymous Runnable object below.
Thread thread2 = new Thread(new Runnable() {
public void run() { for(int i = 0; i < 5; i++) compute(); }
});
// Set the priorities of these two threads, if any are specified
if (args.length >= 1) thread1.setPriority(Integer.parseInt(args[0]));
if (args.length >= 2) thread2.setPriority(Integer.parseInt(args[1]));
// Start the two threads running
thread1.start();
thread2.start();
// This main() method is run by the initial thread created by the
// Java interpreter. Now that thread does some stuff, too.
for(int i = 0; i < 5; i++) compute();
Search WWH ::




Custom Search