![](/img/trans.png)
[英]can't stop a Runnable that passing itself in ScheduledExecutorService.schedule
[英]How to return the return value of the Runnable or Callable passed to ScheduledExecutorService.schedule
public Record task(Id id, Supplier<Record> elector) {
// elector is: '() -> functionName(id, stats)'
final long delayTime = calculateTimeToDelay();
ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
// Cannot resolve method 'schedule(Record, long, TimeUnit)'
return ses.schedule(elector.get(), timeToDelay, TimeUnit.MILLISECONDS);
// try {
// Thread.sleep(delayTime);
// } catch (final InterruptedException e) {
// log.error(e);
// }
// return elector.get();
}
如您所见,注释掉的代码返回了elector.get() 返回的内容,即Record。 但是,我没有使用 Thread.sleep(delayTime),而是尝试使用 ScheduledExecutorService 在几毫秒的延迟后调用lector.get()。 不确定 Runnable 和 Callable 是什么,以及选举者.get() 是否会算作其中之一。
这里的一些方向将不胜感激。
ScheduledExecutorService.schedule
需要Callable
,因此您必须将Supplier
转换为Callable
,例如,通过方法参考语法:
ses.schedule(elector::get, timeToDelay, TimeUnit.MILLISECONDS);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.