定时器
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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步