80,476
社区成员
发帖
与我相关
我的任务
分享
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Timer timer = new Timer();
MyTask task = new MyTask();
MyTask task1 = new MyTask();
timer.schedule(task1, 0, 2000);
Thread.sleep(5000);
task1.cancel();
timer.schedule(task.getCopy(), 5000, 1000);
}
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Timer_cancel {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Timer timer = new Timer();
MyTask task = new MyTask();
timer.schedule(task.getCopy(), 0, 2000);
Thread.sleep(5000);
task.cancel();
timer.schedule(task.getCopy(), 0, 1000);
}
static class MyTask extends TimerTask implements Cloneable {
private MyTask myTask;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName() + "\t" + new Date());
}
public MyTask getCopy() {
if(myTask == null)
myTask = new MyTask();
try {
return (MyTask)myTask.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
}
