Java Reference
In-Depth Information
public static void main(String [] args)
{
Phone phone = new Phone();
phone.startRinging();
try
{
System.out.println(“Phone started ringing...”);
Thread.sleep(20000);
}catch(InterruptedException e)
{}
System.out.println(“Answering the phone...”);
phone.answer();
}
}
Let me make a few comments about the PhoneRinger and Phone classes:
The PhoneRinger class is a TimerTask that keeps track of the number of
rings and displays a simple message in the run() method.
■■
The Phone class instantiates a daemon Timer, so that the Timer will not
keep the application running.
■■
Each time the startRinging() method is invoked to simulate a new
incoming phone call, a new PhoneRinger object is instantiated. You can-
not reuse a previous PhoneRinger object because a task cannot be
rescheduled.
■■
The task is scheduled at a fixed rate, with 0 delay (it starts immediately)
and a 3-second period.
■■
When the Phone is answered, the task is canceled (but not the timer).
This means that the task will not execute again, which in our example
means that the phone will not ring again.
■■
Figure 15.7
Output of the Phone program.
Search WWH ::




Custom Search