Java Reference
In-Depth Information
public void run() {
try {
for (;;) {
System.out.print(word + " ");
Thread.sleep(delay); // wait until next time
}
} catch (InterruptedException e) {
return; // end this thread
}
}
public static void main(String[] args) {
new PingPong("ping", 33).start(); // 1/30 second
new PingPong("PONG", 100).start(); // 1/10 second
}
}
We define a type of thread called
PingPong
. Its
run
method loops forever,
printing its
word
field and sleeping for
delay
milliseconds.
PingPong.run
cannot throw exceptions because
Thread.run
, which it overrides, doesn't
throw any exceptions. Accordingly, we must catch the
InterruptedExcep-
tion
that
sleep
can throw (more on
InterruptedException
later).
Now we can create some working threads, and
PingPong.main
does just
that. It creates two
PingPong
objects, each with its own word and delay
cycle, and invokes each thread object's
start
method. Now the threads
are off and running. Here is some example output:
ping PONG ping ping PONG ping ping ping PONG ping
ping PONG ping ping ping PONG ping ping PONG ping
ping ping PONG ping ping PONG ping ping ping PONG
ping ping PONG ping ping ping PONG ping ping PONG
ping ping ping PONG ping ping PONG ping ping ping
PONG ping ping PONG ping ping ping PONG ping ping ...