0

将 GPars 与 Groovy 一起使用,我启动了 3 个线程来并行执行一些工作......

 GParsPool.withPool(3){ 
   result = myList.collectParallel{
      processItem(it)
   }
 }

这工作正常,但我需要一个代表启动线程号的闭包索引。由于没有循环,因此不确定如何访问这样的索引;一切都在并行发生。

我尝试使用eachWithIndexParallel, 这个,但是 Groovy 抱怨 (ArrayList, Integer) 没有这样的方法

GParsPool.withPool(3) {
    result = myList.eachWithIndexParallel{ i -> 
        processItem( it, i)
    }
}
4

1 回答 1

2

Groovy 中的 eachWithIndex() 将两个参数传递给闭包并且不返回任何结果: GParsPool.withPool(3) { myList.eachWithIndexParallel{e, i -> processItem( e, i) } } 这解释了为什么它找不到该方法。

但是,需要特别注意以线程安全的方式从每个中获取结果。

获取处理元素的线程标识的一种方法是查询闭包内的 Thread.currentThread() 方法。

于 2012-03-01T05:36:18.090 回答