在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
我想做的是延迟闭包将一个已关闭的变量传递给它调用的闭包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)
有什么想法吗?
答案 0 :(得分:1)
我无法重现您的示例,但似乎已经执行了as Callable
部分,并且生成的"hello" + it
正在提交到池中
尝试将Callable
封装在一个闭包中以真正推迟执行:
def defer = { c -> pool.submit({ c(tony) } as Callable) }