TimerTask定时任务与Timer
package org.test3; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class ManyProject { private static Timer timer = new Timer(); private static TimerTask timerTask = null; public static void endTask(String s) { timerTask.cancel(); timerTask = null;//想要再次启动定时此处是关键 System.out.println(s); } public static void startTask(String s) throws InterruptedException { if (timerTask == null) { timerTask = new Task1().getTask1(); } timer.schedule(timerTask, 3000, 2000); } public static void main(String[] args) throws InterruptedException { startTask("启动"); Thread.sleep(6000); endTask("结束"); startTask("再次启动"); } } class Task1 { public TimerTask getTask1() { return new TimerTask() { @Override public void run() { System.out.println("kkkkkk"); } }; } }