Java Reference
In-Depth Information
4.1.1 Java Threads
Java provides two approaches for performing a task in a new thread: 1) defining a subclass
of the Thread class with a run() method that performs the task, and instantiating it; or 2)
defining a class that implements the Runnable interface with a run() method that performs the
task, and passing an instance of that class to the Thread constructor. In either case, the new
thread does not begin execution until its start() method is invoked. The first approach can
only be used for classes that do not already extend some other class; therefore, we focus on the
second approach, which is always applicable. The Runnable interface contains a single method
prototype:
public void run();
When the start() method of an instance of Thread is invoked, the JVM causes the in-
stance's run() method to be executed in a new thread, concurrently with all others. Meanwhile,
the original thread returns from its call to start() and continues its execution independently.
(Note that directly calling the run() method of a Thread or Runnable instance has the normal
procedure-call semantics: the method is executed in the caller's thread.) The exact interleaving
of thread execution is determined by several factors, including the implementation of the JVM,
the load, the underlying OS, and the host configuration. For example, on a uniprocessor sys-
tem, threads share the processor sequentially; on a multiprocessor system, multiple threads
from the same application can run simultaneously on different processors.
In the following example, ThreadExample.java implements the Runnable interface with a
run() method that repeatedly prints a greeting to the system output stream.
ThreadExample.java
0 public class ThreadExample implements Runnable {
1
2
private String greeting;
// Message to print to console
3
4
public ThreadExample(String greeting) {
5
this.greeting = greeting;
6
}
7
8
public void run() {
9
for (;;) {
10
System.out.println(Thread.currentThread().getName() + ": " + greeting);
11
try {
12
Thread.sleep((long) (Math.random() * 100)); // Sleep 0 to 100 milliseconds
13
} catch (InterruptedException e) {} // Will not happen
14
}
15
}
16
17
public static void main(String[] args) {
18
new Thread(new ThreadExample("Hello")).start();
 
Search WWH ::




Custom Search