使用newScheduledThreadPool来模拟心跳机制
(使用newScheduledThreadPool来模拟心跳机制)
1 public class HeartBeat { 2 public static void main(String[] args) { 3 ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); 4 Runnable task = new Runnable() { 5 public void run() { 6 System.out.println("HeartBeat........................."); 7 } 8 }; 9 executor.scheduleAtFixedRate(task,5,3, TimeUnit.SECONDS); //5秒后第一次执行,之后每隔3秒执行一次 10 } 11 }
输出:
HeartBeat....................... //5秒后第一次输出 HeartBeat....................... //每隔3秒输出一个