闭包作为Thread中的参数

时间:2013-01-18 19:16:04

标签: multithreading groovy closures

为什么这段代码不起作用(没有输出)?

clo1 = {
    for(int i =0; i<=10; i++){
        println(i);
    }
}

def thread = Thread.start { clo1 }

但这确实有效:

def thread = Thread.start {
    for(int i =0; i<=10; i++){
        println(i);
    }
}

3 个答案:

答案 0 :(得分:2)

如果你想在线程中执行clo1,你可以这样做

Thread.start clo1 // same as Thread.start(clo1)

Thread.start { clo1() }

第一个将闭包直接传递给Thread.start。第二个解决方案创建一个执行clo1的新闭包。

使用Thread.start { clo1 }只需将新的闭包(无效)传递给Thread.start

答案 1 :(得分:2)

看起来你把一个闭包(clo1)放在传递给Thread.start {clo1}的闭包里面。调用Threat.start clo1将为您提供您期望的结果。

答案 2 :(得分:2)

你在闭包中包装一个闭包

尝试

def thread = Thread.start clo1