Java Reference
In-Depth Information
// Client class
public class
java.lang.Runnable
TaskClass
Client {
...
public void
// Custom task class
public class
someMethod() {
TaskClass
implements
Runnable {
...
// Create an instance of TaskClass
TaskClass task =
...
public
TaskClass(...) {
new
TaskClass(...);
...
}
// Create a thread
Thread thread =
new
Thread(task);
// Implement the run method in Runnable
public void
run() {
// Tell system how to run custom thread
...
}
...
}
// Start a thread
thread.start();
...
}
...
}
(a)
(b)
F
IGURE
30.2
Define a task class by implementing the
Runnable
interface.
Once you have defined a
TaskClass
, you can create a task using its constructor. For
example,
TaskClass task =
new
TaskClass(...);
A task must be executed in a thread. The
Thread
class contains the constructors for cre-
ating threads and many useful methods for controlling threads. To create a thread for a
task, use
Thread
class
create a task
Thread thread =
new
Thread(task);
You can then invoke the
start()
method to tell the JVM that the thread is ready to run, as
follows:
create a thread
thread.start();
The JVM will execute the task by invoking the task's
run()
method. Figure 30.2b outlines
the major steps for creating a task, a thread, and starting the thread.
Listing 30.1 gives a program that creates three tasks and three threads to run them.
start a thread
The first task prints the letter
a
100 times.
■
The second task prints the letter
b
100 times.
■
The third task prints the integers 1 through 100.
■
When you run this program, the three threads will share the CPU and take turns printing letters
and numbers on the console. Figure 30.3 shows a sample run of the program.
F
IGURE
30.3
Tasks
printA
,
printB
, and
print100
are executed simultaneously to
display the letter
a
100 times, the letter
b
100 times, and the numbers from 1 to 100.
Search WWH ::
Custom Search