ScheduledThreadPoolExecutor简单demo
参考: 高并发编程之ScheduledThreadPoolExecutor讲解
import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ScheduledThreadPoolExecutorTest { public static void main(String[] args) { // test01(); test02(); // test03(); } public static void test01() { ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(2); ScheduledFuture future = stpe.schedule(() -> System.out.println("当前时间:" + System.currentTimeMillis()), 2, TimeUnit.SECONDS); //有兴趣可以把下面两行代码的注释去掉玩玩看 //cancel(true):是取消延迟执行 // future.cancel(true); } public static void test02() { ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(2); System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date())); // scheduleAtFixedRate以Runnable#run开始执行的时刻往后推period开始执行 // 在initialDelay时间后,以period的时间间隔执行 stpe.scheduleAtFixedRate(() -> { System.out.println("当前时间:" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + " 我是周期性执行!"); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } }, 1, 5, TimeUnit.SECONDS); } public static void test03() { ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(2); System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date())); // scheduleWithFixedDelay以Runnable#run结束执行的时刻往后推delay开始执行 // 在initialDelay时间后,以delay的时间间隔执行 stpe.scheduleWithFixedDelay(() -> { System.out.println("当前时间:" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + " 我是周期性执行!"); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } }, 1, 5, TimeUnit.SECONDS); } }