2021版Java线程池教程13:如何执行定时、延时任务?介绍 ScheduledExecutorService 接口、ScheduledThreadPoolExecutor 类、schedule 方法。
2021版Java线程池教程13:如何执行定时、延时任务?
视频全集
代码
Task.class
package main;
import java.time.LocalTime;
public class Task implements Runnable {
@Override
public void run() {
System.out.println(LocalTime.now());
}
}
Main.class
package main;
import java.time.LocalTime;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
Task task = new Task();
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
System.out.println(LocalTime.now());
scheduledThreadPool.schedule(task, 3, TimeUnit.SECONDS);
scheduledThreadPool.shutdown();
}
}
|