TimerTask与Timer使用示范
2008-01-05 08:58:25 来源:WEB开发网核心提示:import java.awt.Toolkit;import java.util.Timer;import java.util.TimerTask;/** * Schedule a task that executes once every second. */public class AnnoyingBeep {To
import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;
/**
* Schedule a task that executes once every second.
*/
public class AnnoyingBeep {
Toolkit toolkit;
Timer timer;
public AnnoyingBeep() {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), 0, //initial delay
1 * 1000); //subsequent rate
}
class RemindTask extends TimerTask {
int numWarningBeeps = 3;
public void run() {
if (numWarningBeeps > 0) {
toolkit.beep();
System.out.PRintln("Beep!");
numWarningBeeps--;
} else {
toolkit.beep();
System.out.println("Time's up!");
//timer.cancel(); //Not necessary because we call System.exit
System.exit(0); //Stops the AWT thread (and everything else)
}
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new AnnoyingBeep();
System.out.println("Task scheduled.");
}
}
import java.util.Timer;
import java.util.TimerTask;
/**
* Schedule a task that executes once every second.
*/
public class AnnoyingBeep {
Toolkit toolkit;
Timer timer;
public AnnoyingBeep() {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), 0, //initial delay
1 * 1000); //subsequent rate
}
class RemindTask extends TimerTask {
int numWarningBeeps = 3;
public void run() {
if (numWarningBeeps > 0) {
toolkit.beep();
System.out.PRintln("Beep!");
numWarningBeeps--;
} else {
toolkit.beep();
System.out.println("Time's up!");
//timer.cancel(); //Not necessary because we call System.exit
System.exit(0); //Stops the AWT thread (and everything else)
}
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new AnnoyingBeep();
System.out.println("Task scheduled.");
}
}
更多精彩
赞助商链接