Java Reference
In-Depth Information
Example 4−5: Timer.java (continued)
// Schedule a final task: starting in 5 seconds, count
// down from 5, then destroy the timer, which, since it is
// the only remaining thread, will cause the program to exit.
timer.scheduleAtFixedRate(new TimerTask() {
public int times = 5;
public void run() {
System.out.println(times--);
if (times == 0) timer.cancel();
}
},
5000,500);
}
}
}
Exercises
4-1. Write a Java program that takes a list of filenames on the command line and
prints out the number of lines in each file. The program should create one
thread for each file and use these threads to count the lines in all the files at
the same time. Use java.io.LineNumberReader to help you count lines. You'll
probably want to define a LineCounter class that extends Thread or imple-
ments Runnable . Now write a variant of your program that uses your
LineCounter class to read the files sequentially, rather than at the same time.
Compare the performance of the multithreaded and single-threaded pro-
grams, using System.currentTimeMills() to determine elapsed time. Com-
pare the performance of the two programs for two, five, and ten files.
4-2. Example 4-3 demonstrates how deadlock can occur when two threads each
attempt to obtain a lock held by the other. Modify the example to create
deadlock among three threads, where each thread is trying to acquire a lock
held by one of the other threads.
4-3. Example 4-3 uses the synchronized statement to demonstrate deadlock. Write
a similar program that causes two threads to deadlock, but use synchronized
methods instead of the synchronized statement. This sort of deadlock is a lit-
tle more subtle and harder to detect.
4-4. Example 4-5 shows an implementation of the Java 1.3 java.util.Timer API.
Java 1.2 introduced another Timer class, the javax.swing.Timer class. This
class has a similar purpose but a different API. It invokes the actionPer-
formed() method of any number of registered ActionListener objects one or
more times after a specified delay and at a specified interval. Read the docu-
mentation for this Timer class, then create your own implementation of it. If
you've read Chapter 10, Graphical User Interfaces , you know that the meth-
ods of event listeners, such as the actionPerformed() method, are supposed
to be invoked only by the event dispatch thread. Therefore, your implementa-
tion of the Timer class should not invoke actionPerformed() directly, but
should instead use java.awt.EventQueue.invokeLater() or
javax.swing.SwingUtilities.invokeLater() to tell the event dispatch thread
to invoke the method.
Search WWH ::




Custom Search