试着使用Timer类编写一个简单的计时器(java)

来源:百度知道 编辑:UC知道 时间:2024/05/31 04:21:31
让程序在启用Timer100毫秒后执行TimerTask所描述额度任务(模拟让一个虚拟计算机BIOS主板鸣音三次,并打印出鸣音记录),然后每一秒钟执行一次,执行三次后取消该任务,同时取消计时器,程序退出。

import java.util.*;
public class Test
{
public static void main(String[] args)
{
Timer t=new Timer();
t.schedule(new task(),100,1000);
}
}

class task extends TimerTask
{
public void run()
{
int count=0;
for(int i=0;i<3;i++)
{
System.out.println("鸣音~~~~~~~~~~~~~~~~~~");
System.out.println("第"+(count+1)+"次鸣音!");
count++;
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.exit(0);
}
}