【问题标题】:Passing a variable to a closure that is executed as a callable将变量传递给作为可调用对象执行的闭包
【发布时间】:2014-05-27 16:30:57
【问题描述】:

在 Groovy 中我们可以做到这一点...

def pool = Executors.newFixedThreadPool(1)
def defer = { c -> pool.submit(c as Callable) }   

def myfunction = {"hello"}
def deferedInvocation = defer(myfunction)

def response = deferedInvocation.get() 
println response    // outputs hello

我想做的是让 defer 闭包将其关闭的变量之一传递到它调用的闭包 c 中。

所以我们有一个外部变量tony

类似这样的:

def tony = "tony"
def pool = Executors.newFixedThreadPool(1)
def defer = { c -> pool.submit(c(tony) as Callable) }   // tony is closed variable

def myfunction = {"hello " + it}
def deferedInvocation = defer(myfunction)

def response = deferedInvocation.get() 
println response

但是,当我尝试得到:

java.util.concurrent.ExecutionException: org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack: No signature of method: java.lang.String.call() is applicable for argument types: () values: []
Possible solutions: wait(), any(), wait(long), each(groovy.lang.Closure), any(groovy.lang.Closure), take(int)

有什么想法吗?

【问题讨论】:

    标签: groovy closures


    【解决方案1】:

    我无法重现您的示例,但似乎 as Callable 部分已执行,并且生成的 "hello" + it 正在提交到池中

    尝试将Callable 封装在一个闭包中以真正推迟执行:

    def defer = { c -> pool.submit({ c(tony) } as Callable) }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      相关资源
      最近更新 更多