使用带有Groovy的GPars,我启动了3个线程来并行完成一些工作。。。
GParsPool.withPool(3){
result = myList.collectParallel{
processItem(it)
}
}
这很好,但我需要在闭包中有一个索引来表示启动的线程号。不知道如何访问这样的索引,因为没有循环;一切都在并行发生。
我尝试过使用eachWithIndexParallel
,但是Groovy抱怨(ArrayList,Integer)没有这样的方法
GParsPool.withPool(3) {
result = myList.eachWithIndexParallel{ i ->
processItem( it, i)
}
}
eachWithIndex()向闭包传递两个参数,但不返回结果:GParsPool.withPool(3){myList.eeachWithIndexParallel{e,i->processItem(e,i)}}这就解释了它为什么找不到该方法。
然而,需要特别小心,以线程安全的方式获得每个结果。
获取处理元素的线程标识的一种方法是查询闭包中的thread.currentThread()方法。