Chapter 15 Lab 15.3: Using Timer and TimerTask To become familiar with using the
ID: 3640747 • Letter: C
Question
Chapter 15 Lab 15.3: Using Timer and TimerTask To become familiar with using the Timer and TimerTask class. Write a class named Reminder that extends TimerTask Add a field of type String named message, and a constructor that initializes this field. Within the run() method, simply print out the message field using System out printin(). Write a class named TestReminder that contains main(). Within main(), instantiate a new Timer object. Within main(), instantiate three Reminder objects, each with a different message. Using the schedule() method of the Timer class that creates a single execution task, schedule your three Reminder objects with the Timer. Have the first Reminder scheduled immediately, the second reminder after 30 seconds, and the third reminder after 2 minutes. Save, compile, and run the TestReminder program. The three reminders should be displayed at the command prompt. You should have to wait 2 minutes before seeing the final reminder.Explanation / Answer
public class Reminder extends java.util.TimerTask {private String message;
Reminder(String message) {
this.message = message;
}
public void run() {
System.out.println(this.message);
}
}
class TestReminder {
public static void main(String[] args) {
java.util.Timer timer = new java.util.Timer();
System.out.println("Assigning Reminder Tasks");
timer.schedule(new Reminder("one sec reminder"), 0, 1*1000);
timer.schedule(new Reminder("thirty sec reminder"), 0, 1*30*1000);
timer.schedule(new Reminder("two minute reminder"), 0, 2*60*1000);
}
} public class Reminder extends java.util.TimerTask {
private String message;
Reminder(String message) {
this.message = message;
}
public void run() {
System.out.println(this.message);
}
}
class TestReminder {
public static void main(String[] args) {
java.util.Timer timer = new java.util.Timer();
System.out.println("Assigning Reminder Tasks");
timer.schedule(new Reminder("one sec reminder"), 0, 1*1000);
timer.schedule(new Reminder("thirty sec reminder"), 0, 1*30*1000);
timer.schedule(new Reminder("two minute reminder"), 0, 2*60*1000);
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.