Asynchronous 在grails PromiseMap中,如何阻止当前线程,以便所有并发任务完成并返回其结果?
我需要异步获取猫、狗和老鼠,然后进行一些后处理。以下是我正在做的事情:Asynchronous 在grails PromiseMap中,如何阻止当前线程,以便所有并发任务完成并返回其结果?,asynchronous,grails3,Asynchronous,Grails3,我需要异步获取猫、狗和老鼠,然后进行一些后处理。以下是我正在做的事情: Promise<List<Cat>> fetchCats = task {} Promise<List<Mouse>> fetchMice = task { } Promise<List<Dog>> fetchDogs = task {} List promiseList = [fetchCats, fetchMice, fetchDogs] Li
Promise<List<Cat>> fetchCats = task {}
Promise<List<Mouse>> fetchMice = task { }
Promise<List<Dog>> fetchDogs = task {}
List promiseList = [fetchCats, fetchMice, fetchDogs]
List results = Promises.waitAll(promiseList)
虽然PromiseMap
有一个onComplete
方法,但它不会让当前线程等待所有承诺完成
使用
PromiseMap
,如何阻止当前线程直到所有承诺完成?如果您只关心当前线程等待PromiseMap完成,可以使用thread:join()
使用.get()
从PromiseMap来源:
/**
*同步返回已填充的映射,其中包含从已使用的映射中获取的所有值
*在填充的地图中
*
*@return一个从承诺中获取值的映射
*/
Map get()抛出可丢弃的{
import grails.async.*
def map = new PromiseMap()
map['one'] = { 2 * 2 }
map['two'] = { 4 * 4 }
map['three'] = { 8 * 8 }
map.onComplete { Map results ->
assert [one:4,two:16,three:64] == results
}
import grails.async.*
def map = new PromiseMap()
map['one'] = { println "task one" }
map['two'] = { println "task two" }
map['three'] = { println "task three" }
Thread t = new Thread() {
public void run() {
println("pausing the current thread, let promiseMap complete first")
map.onComplete { Map results ->
println("Promisemap processing : " + results)
}
}
}
t.start()
t.join()
println("\n CurrentThread : I can won the race if you just comment t.join() line in code")
/**
* Synchronously return the populated map with all values obtained from promises used
* inside the populated map
*
* @return A map where the values are obtained from the promises
*/
Map<K, V> get() throws Throwable {