|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
- Question: What method in
TimerorTimerTaskcan you use to determine when the task was most recently scheduled to execute? (Hint: You can find the answer by looking at the API documentation forTimerandTimerTask. Remember that these classes were introduced in version 1.3 of the Java platform.)Answer: The
TimerTaskscheduledExecutionTimemethod.
- Question: What is the effect of calling the
startmethod on aThreadobject?Answer: The thread goes into the Runnable state and the
runmethod is invoked.
- Question: What are the two ways you can provide the implementation for a thread's
runmethod?Answer:
- Create a
Threadsubclass that overrides therunmethod.- Write a class that implements the
Runnableinterface and therunmethod.
- Exercise: Convert
AnnoyingBeep.javaso that the initial delay is 5 seconds, instead of 0.
Solution: Change the initial delay argument to the
schedulemethod from 0 to 5*1000.
- Exercise: Convert
AnnoyingBeep.javato use the
scheduleAtFixedRatemethod instead ofscheduleto schedule the task. Change the implementation of therunmethod so that if therunmethod is called too late for a warning beep (say, more than 5 milliseconds after it was scheduled to run), nothing happens--no beep and string are generated. (Hint: Remember your answer to question 1.)Solution: Substitute
scheduleAtFixedRateforschedule. You can useSystem.currentTimeMillis()to get the current time to compare with the scheduled execution time. A full solution is inSkippingBeep.java.
- Exercise: Change the main program of
TwoThreadsDemo.javaso that it creates a third thread, named "Bora Bora." ” Compile and run the program again. Note that you will also need
SimpleThread.java. Does this change your vacation destiny?
Solution: Add the following line to the
mainmethod:new SimpleThread("Bora Bora").start();- Exercise: Compile and run
RaceDemo.javaand
SelfishRunner.javaon your computer. Do you have a time-sliced system?
Solution: The answer depends on your system. As of JDK 1.0, the Java VM on Microsoft Windows (includes Windows 95/98/NT/2000) uses time slicing while the Java VM on Solaris does not.
- Exercise: Well-behaved threads voluntarily relinquish the CPU periodically and give other threads an opportunity to run. Rewrite the
SelfishRunnerclass to be a
PoliteRunner. Be sure to modify the main program inRaceDemo.javato create
PoliteRunners instead ofSelfishRunners.Solution: Add a call to the
yieldmethod somewhere within therunmethod, such as just after the call toprintln.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.