Java Reference
In-Depth Information
word = whatToSay;
delay = delayTime;
}
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) {
Runnable ping = new RunPingPong("ping", 33);
Runnable pong = new RunPingPong("PONG", 100);
new Thread(ping).start();
new Thread(pong).start();
}
}
First, a new class that implements
Runnable
is defined. Its implementa-
tion of the
run
method is the same as
PingPong
's. In
main
, two
RunPingPong
objects with different timings are created; a new
THRead
object is then
created for each object and is started immediately.
Five
Thread
constructors enable you to specify a
Runnable
object:
public
Thread(Runnable target)
Constructs a new
THRead
that uses the
run
method of the spe-
cified
target
.
public
Thread(Runnable target, String name)