[英]How to make a runnable terminate early
I have a runnable, the code below, whenever it's called in 10 seconds it should do whatever. 我有一个可运行的代码,下面的代码,只要在10秒钟内调用它,它就应该执行任何操作。
CoresManager.slowExecutor.schedule(new Runnable() {
@Override
public void run() {
try {
if (isAtWildSafe()) {
player.sm("This area is now safe for you.");
player.setCanPvp(false);
player.safeWait = false;
removeIcon();
}
} catch (Throwable e) {
Logger.handle(e);
}
}
}, 10, TimeUnit.SECONDS);
But, lets say 5 seconds has gone by, and I want to cancel the runnable before it can do its action. 但是,可以说5秒钟过去了,我想取消可运行对象,然后再执行操作。 How would I achieve this without canceling all the active runnables.
我如何在不取消所有活动可运行对象的情况下实现这一目标。
The schedule(...)
method should return a Future
object. schedule(...)
方法应返回一个Future
对象。 The Future
API has a cancel(...)
method. Future
API具有cancel(...)
方法。
So to achieve what you want to do: save the Future
object somewhere and then call cancel
on it after 5 seconds. 因此,要实现您要执行的操作:将
Future
对象保存在某个位置,然后在5秒钟后对其调用cancel
。 Note that it is OK to cancel a future that has already been run. 请注意,可以取消已经运行的将来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.