Kxgx.com - 移动开发网

本站快讯:
搜索: 您的位置主页>参考源码>软件源码>>阅读源码:TimerTask与Timer使用示范

TimerTask与Timer使用示范

2006-02-16   来源:   作者:未知   【 】 评论:0条
本例说明了如何使用Timer和TimerTask周期性的执行一些任务。当然你也可以使用Thread来完成这些任务。 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
        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.");
  }
}
Tags:  
责任编辑:
  • 请文明参与讨论,禁止漫骂攻击。 用户名:新注册)密码:匿名:
    评论总数:0 [ 查看全部 ] 网友评论
    关于我们 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 帮助