GPars:返回每个并行{}

Jak*_*nar 6 groovy gpars

我想用这些示例字符串中的每一个做很多东西,并在这里返回一些其他类型的Object Integers,稍后是一些更大的类对象.

在这个例子中,我正在尝试一些简单的事情,但是我怎么会得到一个完全错误的结果.至少对于我希望得到的东西.的xD

我希望得到:[6, 5, 6, 5] 但我得到:[butter, bread, dragon, table]

package test

@Grab(group='org.codehaus.gpars', module='gpars', version='1.0.0')
import static groovyx.gpars.GParsPool.withPool

class Test {
    List<String> strings = new ArrayList<String>([
        "butter",
        "bread",
        "dragon",
        "table"
    ])

    def closure = { it.length() }

    def doStuff() {
        def results = withPool( 4 ) {
            strings.eachParallel{ it.length()}
        }
        println results
    }

    static main(args) {
        def test = new Test()
        test.doStuff()
    }
}
Run Code Online (Sandbox Code Playgroud)

如果答案可以有一个简短的解释,那将是很好的.非常感谢!

tim*_*tes 11

在groovy中,each(和eachParallel在GPars中)返回原始集合.

你想要的是collect(通过调用闭包返回新的集合)

所以,改变

        strings.eachParallel { it.length() }
Run Code Online (Sandbox Code Playgroud)

        strings.collectParallel { it.length() }
Run Code Online (Sandbox Code Playgroud)

(顺便说一句)

GPars现在捆绑了Groovy所以你不应该需要它@Grab,我假设你打算在你的closure变量中使用collect

package test

import static groovyx.gpars.GParsPool.withPool

class Test {
  List<String> strings =  [ "butter", "bread", "dragon", "table" ]

  def closure = { it.length() }

  def doStuff() {
    def results = withPool( 4 ) {
      strings.collectParallel closure
    }
    println results
  }

  static main( args ) {
    def test = new Test()
    test.doStuff()
  }
}
Run Code Online (Sandbox Code Playgroud)