问题描述
kotlin函数delay()
具有以下规范:
我想使用Java实现确切的功能。基本上,我需要使用一些延迟来运行函数,并且该函数应该可以在任何给定条件下随时取消。
我已经经历过this线程,但是大多数答案都不太适合我的情况。
解决方法
您正在寻找ScheduledExecutorService
。
// Create the scheduler
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(1);
// Create the task to execute
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello");
}
};
ScheduledFuture<?> scheduledFuture =
scheduledExecutorService. schedule(r,5,TimeUnit.SECONDS);
// Cancel the task
scheduledFuture.cancel(false);
取消时会抛出InterruptedException
。