public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime localDateTime = LocalDateTime.now(); String format = localDateTime.format(formatter); System.out.println("1:"+format); Timer timer = new Timer(); for (int i = 0; i < 2; i++) { timer.schedule(new TimerTask() { @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread name : "+ Thread.currentThread().getName()); LocalDateTime localDateTime = LocalDateTime.now(); String format = localDateTime.format(formatter); System.out.println("2:"+format); } }, 3000); } localDateTime = LocalDateTime.now(); format = localDateTime.format(formatter); System.out.println("3:"+format); }
結果git
1:2019-10-14 17:35:13 3:2019-10-14 17:35:13 Thread name : Timer-0 2:2019-10-14 17:35:19 Thread name : Timer-0 2:2019-10-14 17:35:22
ScheduledExecutorService
作了改進,採用了線程池的定時任務隊列,實際使用的也是最小堆排序private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) { // timerTest(); print("1:"); ScheduledExecutorService service = new ScheduledThreadPoolExecutor(2); for (int i = 0; i < 2; i++) { service.schedule(new Runnable() { @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread name : " + Thread.currentThread().getName()); print("2:"); } }, 3, TimeUnit.SECONDS); } print("3:"); service.shutdown(); } private static void print(String s) { LocalDateTime localDateTime = LocalDateTime.now(); String format = localDateTime.format(formatter); System.out.println(s + format); }
結果github
1:2019-10-15 11:53:54 3:2019-10-15 11:53:54 Thread name : pool-1-thread-1 2:2019-10-15 11:54:00 Thread name : pool-1-thread-2 2:2019-10-15 11:54:00
明白它的延遲原理和Timer同樣,能夠知道若是我把核心線程數改爲1,則效果和Timer相似數組
1:2019-10-15 11:57:40 3:2019-10-15 11:57:40 Thread name : pool-1-thread-1 2:2019-10-15 11:57:46 Thread name : pool-1-thread-1 2:2019-10-15 11:57:49
參考博客:
延遲消息之時間輪多線程