new一個(gè)線程數(shù)為4的線程池:
ScheduledExecutorService service = Executors.newScheduledThreadPool(4);
官方API提供四個(gè)方法如圖:
即興翻譯:
1.schedule(Callable<V> callable, long delay, TimeUnit unit)
創(chuàng)建并執(zhí)行并銷毀一個(gè)callable在延遲指定delay時(shí)間后
2.同1,callable換成了runnable
3.scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
創(chuàng)建并執(zhí)行并結(jié)束一個(gè)runnable在延遲指定initialDelay時(shí)間,然后,每隔initialDelay+period*n時(shí)間執(zhí)行一次
4.scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
創(chuàng)建并執(zhí)行并結(jié)束一個(gè)runnable在延遲指定initialDelay時(shí)間,然后第一次執(zhí)行完成后,間隔delay時(shí)間繼續(xù)執(zhí)行一次,無限循環(huán)。
測試代碼:
難點(diǎn):
1.scheduleAtFixedRate如果執(zhí)行時(shí)間小于指定的間隔時(shí)間的情況下,callable或runnable每隔period執(zhí)行一次,如果執(zhí)行時(shí)間大于指定的間隔時(shí)間,每隔程序執(zhí)行時(shí)間執(zhí)行一次。
2.scheduleWithFixedDelay,不管執(zhí)行時(shí)間怎么樣,兩次執(zhí)行時(shí)間之間必須間隔delay時(shí)間。