异步函数的使用
闭包增强
Groovy 提供了大量基础设施,使高效的函数式编程成为可能。闭包可以存储在变量中,作为参数和返回值传递,组合,记忆化,弹跳或部分应用。
GPars 将异步性添加到混合中。闭包现在可以是同步或异步的,或者,如果您愿意,可以同时是两者。您可以在单个计算中混合同步和异步闭包,没有限制。
GParsExecutorsPool.withPool 示例
1
2
3
4
5
6
7
8
9
GParsExecutorsPool.withPool {
/**
* The callAsync() method is an asynchronous variant
* of the default call() method to invoke a closure.
* It will return a Future for the result value.
*/
assert 6 == {it * 2}.call(3)
assert 6 == {it * 2}.callAsync(3).get()
}
示例
GParsPool.withPool 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
GParsPool.withPool {
Closure longLastingCalculation = {calculate()}
//create a new closure, which starts the original closure on a thread pool
Closure fastCalculation = longLastingCalculation.asyncFun()
//returns almost immediately
Promise result=fastCalculation()
//do stuff while calculation performs ???
...
//finally ask for the result, blocking, if not yet available
println result.get()
}
有关异步计算的更多详细信息,请访问用户指南中的异步调用部分。