ScheduledExecutorService 是 JDK 提供的一個(gè)接口,用于定時(shí)執(zhí)行任務(wù)??梢酝ㄟ^(guò)以下步驟來(lái)實(shí)現(xiàn) ScheduledExecutorService:
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
Runnable task = new Runnable() {
public void run() {
// 任務(wù)執(zhí)行的邏輯
}
};
executorService.schedule(task, 1, TimeUnit.SECONDS);
以上代碼表示任務(wù)將在 1 秒后執(zhí)行。
executorService.shutdown();
完整示例代碼如下:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledExecutorServiceExample {
public static void main(String[] args) {
// 創(chuàng)建 ScheduledExecutorService 對(duì)象
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
// 創(chuàng)建任務(wù)對(duì)象
Runnable task = new Runnable() {
public void run() {
System.out.println("執(zhí)行任務(wù)");
}
};
// 安排任務(wù)的執(zhí)行
executorService.schedule(task, 1, TimeUnit.SECONDS);
// 關(guān)閉 ScheduledExecutorService
executorService.shutdown();
}
}
這樣就完成了使用 ScheduledExecutorService 來(lái)定時(shí)執(zhí)行任務(wù)的實(shí)現(xiàn)。