赞
踩
JAVA用于执行周期性任务的线程池:
ScheduledExecutorService
ScheduledExecutorService的继承关系
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
示例:每隔1s打印一次hello world
@Slf4j
public class ThreadTest {
private static ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
public static void main(String[] args) {
log.info("task begin");
executorService.scheduleAtFixedRate(() -> {
log.info("hello world !");
}, 1, 1, TimeUnit.SECONDS);
}
}
运行结果:
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);
示例:每隔1s打印一次hello world
@Slf4j
public class ThreadTest {
private static ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
public static void main(String[] args) {
log.info("task begin");
executorService.scheduleWithFixedDelay(() -> {
log.info("hello world !");
}, 1, 1, TimeUnit.SECONDS);
}
}
运行结果:
两个方法都可以执行周期性的任务,在任务执行时间比较短时,小于任务执行周期的时候,两者几乎看不出什么区别
当任务执行时间大于任务执行周期的时候,如下案例
我们让两个方法执行周期都是1s,任务执行时间变成2s
@Slf4j public class ThreadTest { private static ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1); public static void main(String[] args) { log.info("task begin"); executorService.scheduleAtFixedRate(() -> { log.info("hello world !"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } }, 1, 1, TimeUnit.SECONDS); } }
执行结果:
@Slf4j
public class ThreadTest {
private static ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
public static void main(String[] args) {
log.info("task begin");
executorService.scheduleWithFixedDelay(() -> {
log.info("hello world !");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1, 1, TimeUnit.SECONDS);
}
}
执行结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。