例子如下:
import java.io.IOException;
import java.util.Timer;
public class TimerTest{
static Timer timer;
public static void main(String[]args)
{
timer = new Timer();
timer.schedule(new MyTask(), 1000L, 1000L);
while(true)
{
try{
int ch = System.in.read();
if (ch -'c' == 0){
timer.cancel();
isCancel = true;
}
if (ch - 'q' == 0){
if (!isCancel)
timer.cancel();
break;
}
if (ch - 'b' == 0){
if (isCancel){
timer = new Timer();
timer.schedule(new MyTask(), 1000L, 1000L);
isCancel = false;
i = 0;
}
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
static int i = 0;
static boolean isCancel = false;
static class MyTask extends java.util.TimerTask
{
public void run()
{
i += 1;
System.out.println("......"+i+"s........");
}
}
}
简单的表示了Timer的用法,使用过程中发现timer无法通过api获得是否已经cancel掉了。不知道是用的不对还是本就如此,所以我用了一个标志位isCancel来识别是否cancel掉了。从印象里这种用法是不大标准的...