Groovy并发 [英] Groovy concurrency
问题描述
我的任务是以特定的方式转换给定目录中的每个文件
并将结果输出在一个文件中的其他目录。
我写了下面的代码,它可以工作:
static def translateDir(fromDir,targetDir){
def allFiles = new File(fromDir).listFiles()
def numFiles = allFiles.length
for (我在0 ..(numFiles - 1))
translate(allFiles [i] .getAbsolutePath(),targetDir)
}
现在,我尝试像下面这样并行化这段代码:
static def translateDir(fromDir,targetDir){
def allFiles = new File(fromDir).listFiles()
def numFiles = allFiles.length
def numCores = Runtime.getRuntime()。availableProcessors()
for(i in 0 ..(numCores - 1)){
println(Thread+ i +starting)
Thread.start {
for(def j = i; j< numFiles; j + = numCores){
println(j =+ j)
translate(allFiles [j] .getAbsolutePath(),targetDir)
}
}
}
}
这不起作用并提供输出:
线程0开始
线程1开始
线程2开始
线程3开始
这里发生了什么?
好的,2件事:
-
在线程的隐式run()方法中,引用'i'变量。我不得不通过一个调试器来查看究竟发生了什么,但从技术上讲,你甚至不应该访问'我'那里,因为它不是最终的。所以,我建议创建一个Runnable对象,在构造函数中将i传递给它。然后在线程上启动runnable。
Groovy具有很好的并发支持 - 没有理由像这样推出自己的产品。查看 GPars
I have a question to Groovy threads.
My task is to translate each file in a given directory in a certain manner and place the resulting output in a file in an other directory.
I wrote the following code, which works:
static def translateDir(fromDir, targetDir) {
def allFiles = new File(fromDir).listFiles()
def numFiles = allFiles.length
for (i in 0..(numFiles - 1))
translate(allFiles[i].getAbsolutePath(), targetDir)
}
Now, I tried to parallelize this code like this:
static def translateDir(fromDir, targetDir) {
def allFiles = new File(fromDir).listFiles()
def numFiles = allFiles.length
def numCores = Runtime.getRuntime().availableProcessors()
for (i in 0..(numCores - 1)) {
println("Thread " + i + "starting")
Thread.start {
for (def j = i; j < numFiles; j += numCores) {
println("j = " + j)
translate(allFiles[j].getAbsolutePath(), targetDir)
}
}
}
}
which does not work and provides the output:
Thread 0 starting
Thread 1 starting
Thread 2 starting
Thread 3 starting
nunCores is 4, and numFiles is 3 in my test case. What is going on here?
ok, 2 things:
Inside of the thread's implicit run() method, you are referencing the 'i' variable. I'd have to step it through a debugger to see exactly what happens, but technically, you shouldn't even have access to 'i' there, because it's not final. So, I'd suggest creating a Runnable object to which you pass 'i' in the constructor. Then start the runnable on the thread.
Groovy has great concurrency support - no reason to roll your own like this. Take a look at GPars
这篇关于Groovy并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!