虽然过去
java.util.Timer曾经是安排未来任务的好方法,但现在最好使用1代替
java.util.concurrent包中的类。
有一个
ScheduledExecutorService专门设计用于延迟后运行命令(或定期执行命令,但这与该问题无关)。
它有一种
schedule(Runnable, long,TimeUnit)方法
创建并执行一次操作,该操作在给定的延迟后启用。
使用a
ScheduledExecutorService可以这样重新编写程序:
import java.util.concurrent.*;public class Scratch { private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public static void main(String[] args) { System.out.println("Starting one-minute countdown now..."); ScheduledFuture<?> countdown = scheduler.schedule(new Runnable() { @Override public void run() { // do the thing System.out.println("Out of time!"); }}, 1, TimeUnit.MINUTES); while (!countdown.isDone()) { try { Thread.sleep(1000); System.out.println("do other stuff here"); } catch (InterruptedException e) { e.printStackTrace(); } } scheduler.shutdown(); }}通过这种方式获得的好处之一就是
ScheduledFuture<?>从调用中得到的对象
schedule()。
这样,您就可以摆脱多余的
boolean变量,而直接检查作业是否已运行。
如果您不想再等待计划的任务,则可以通过调用其
cancel()方法来取消它。
1看到Java Timer vsExecutorService吗?出于避免使用
Timer赞成的原因
ExecutorService。



