THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

private String word; // what word to print
private int delay; // how long to pause


public PingPong(String whatToSay, int delayTime) {
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) {
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 InterruptedException 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 ...


You can give a thread a name, either as a String parameter to the constructor or as the parameter of a
setName invocation. You can get the current name of a thread by invoking getName. Thread names are
strictly for programmer conveniencethey are not used by the runtime systembut a thread must have a name
and so if none is specified, the runtime system will give it one, usually using a simple numbering scheme like
Thread-1, Thread-2, and so on.


You can obtain the Thread object for the currently running thread by invoking the static method
THRead.currentThread. There is always a currently running thread, even if you did not create one
explicitlymain itself is executed by a thread created by the runtime system.


Exercise 14.1: Write a program that displays the name of the thread that executes main.

Free download pdf