未来声明似乎独立于承诺
Future declaration seems independent from promise
我正在阅读这篇文章 http://danielwestheide.com/blog/2013/01/16/the-neophytes-guide-to-scala-part-9-promises-and-futures-in-practice.html 我正在查看这段代码:
object Government {
def redeemCampaignPledge(): Future[TaxCut] = {
val p = Promise[TaxCut]()
Future {
println("Starting the new legislative period.")
Thread.sleep(2000)
p.success(TaxCut(20))
println("We reduced the taxes! You must reelect us!!!!1111")
}
p.future
}
}
我已经看过几次这种类型的代码,但我很困惑。所以我们有这个Promise
:
val p = Promise[TaxCut]()
还有这个Future
:
Future {
println("Starting the new legislative period.")
Thread.sleep(2000)
p.success(TaxCut(20))
println("We reduced the taxes! You must reelect us!!!!1111")
}
我没有看到它们之间有任何分配,所以我不明白:它们是如何连接的?
I don't see any assignment between them so I don't understand: How are
they connected?
A Promise
是创建 Future
的一种方法。
当您使用 Future { }
并导入 scala.concurrent.ExecutionContext.Implicits.global
时,您是在 Scala 的线程池线程之一上排队一个函数。但是,这不是生成 Future
的唯一方法。 Future
不一定要安排在不同的线程上。
这个例子所做的是:
- 创建一个
Promise[TaxCut]
,将在不久的将来完成。
- 通过
Future
应用将函数排队 运行 在线程池线程中。该函数还通过Promise.success
方法完成了Promise
- Returns 通过
Promise.future
承诺产生的未来。当这个未来 returns 时,它可能还没有完成,这取决于排队到 Future
的函数的执行速度有多快(OP 试图通过 Thread.sleep
传达这一点方法,延迟未来的完成)。
我正在阅读这篇文章 http://danielwestheide.com/blog/2013/01/16/the-neophytes-guide-to-scala-part-9-promises-and-futures-in-practice.html 我正在查看这段代码:
object Government {
def redeemCampaignPledge(): Future[TaxCut] = {
val p = Promise[TaxCut]()
Future {
println("Starting the new legislative period.")
Thread.sleep(2000)
p.success(TaxCut(20))
println("We reduced the taxes! You must reelect us!!!!1111")
}
p.future
}
}
我已经看过几次这种类型的代码,但我很困惑。所以我们有这个Promise
:
val p = Promise[TaxCut]()
还有这个Future
:
Future {
println("Starting the new legislative period.")
Thread.sleep(2000)
p.success(TaxCut(20))
println("We reduced the taxes! You must reelect us!!!!1111")
}
我没有看到它们之间有任何分配,所以我不明白:它们是如何连接的?
I don't see any assignment between them so I don't understand: How are they connected?
A Promise
是创建 Future
的一种方法。
当您使用 Future { }
并导入 scala.concurrent.ExecutionContext.Implicits.global
时,您是在 Scala 的线程池线程之一上排队一个函数。但是,这不是生成 Future
的唯一方法。 Future
不一定要安排在不同的线程上。
这个例子所做的是:
- 创建一个
Promise[TaxCut]
,将在不久的将来完成。 - 通过
Future
应用将函数排队 运行 在线程池线程中。该函数还通过Promise.success
方法完成了Promise
- Returns 通过
Promise.future
承诺产生的未来。当这个未来 returns 时,它可能还没有完成,这取决于排队到Future
的函数的执行速度有多快(OP 试图通过Thread.sleep
传达这一点方法,延迟未来的完成)。