我有一个类,它的内部线程在一系列操作上运行,它只会不断循环执行操作。为此,它将读取通知队列,告知其下一步要执行的操作。有一条通知告诉班级停止所有动作并杀死自己。当另一个线程调用notifyClose通知时,它添加到队列中并获得优先级为1。我希望添加通知的方法在另一个线程处理关闭通知时返回Future.success。
代码运行如下:
def loop(): Future[Unit] = {
current = if(queue.contains(KILL)) disable() // <--- disable will set the state to Closed
else process() // <--- if queue is empty it will call loop(),
// if its not empty it will do de action and then call loop()
}
private def disable(): Future[Unit] = {
state = Closed
Future.unit
}
def close(): Future[Unit] = {
queue.add(KILL)
while (state != Closed) { /* Wait until state is NotAvailable */ }
Future.successful()
}
我想要一种更好的方法来等待,直到在close()
方法中将状态更改为“已关闭”。我填补了这个空白,空循环是有史以来最糟糕的想法。
可变电流持有正在处理的当前期货,也许有一种方法可以将我的结果与该期货挂钩?问题是我不知道disable()
方法何时真正开始。任何帮助将不胜感激。感谢您抽出宝贵的时间阅读。
例如,尝试使用Promise
作为一种状态
Promise
通过这种方式,def loop(): Future[Unit] = {
if(queue.contains(KILL)) Future.successful(disable.trySuccess())
else process()
}
private val disable = Promise[Unit]()
def close(): Future[Unit] = {
queue.add(KILL)
disable.future
}
返回的Future
仅在close()
实际调用loop()
时才能完成。