1,使用Timer和TimerTask(实现了Runnable接口)
public class TimerTest { public static void main(String[] args){ TimerTask task = new TimerTask() { @Override public void run() { System.out.println("hi"); } }; Timer timer = new java.util.Timer(); timer.scheduleAtFixedRate(task,0,1000);//第二个参数代表首次延迟执行时间,第三个参数代表定时周期,单位毫秒 } }2,使用Concurrent并发包下的ScheduleExecutorService
public class TimerTest { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { System.out.println("hi"); } }; ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor();//定时执行 // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间 service.scheduleAtFixedRate(runnable, 10, 1, TimeUnit.SECONDS); } }通过线程池执行任务,性能比Timer单线程的好.