public class ThreadTest { class MyTask implements Runnable{ public void run() { say(); } } public void init(){ say(); MyTask myTask = new MyTask(); ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); executorService.scheduleAtFixedRate(myTask,5,5,TimeUnit.SECONDS); } public static void say(){ System.out.println("Hello world"); } public static void main(String[] args) { ThreadTest threadTest = new ThreadTest(); threadTest.init(); }}
这个程序执行了之后,在运行这个程序后的5秒(scheduleAtFixedRate的第二个参数决定)之后,每5秒(scheduleAtFixedRate的第三个参数决定)执行一个say().