public class Demo { private long time;//间隔的时间 private Runnable task;//指定的任务 private boolean flag = true; private Thread th = null;//默认为null public static void main(String[] args) { Demo de=new Demo(2L,new person()); } public Demo(long time, Runnable task) { this.time = time; this.task = task; } public void start() { if(th == null) { // 一旦调用了start()方法后,th就不会在是null了。 th = new Thread(new Runnable() { public void run() { while(flag) { task.run(); try { Thread.sleep(time); } catch(InterruptedException e) {} } } }); th.start(); } else { throw new RuntimeException("定时器已经启动,不能再次启动!"); } } public void stop() { this.flag = false; } }
public class Test { public static void main(String[] args) throws InterruptedException { MyTimer mt = new MyTimer(2000, new Runnable() { public void run() { System.out.println("Hello World!"); } }); mt.start(); Thread.sleep(10000); mt.stop(); } } 青春 22:34:17