1

我正在读这个:A closure looks a lot like a regular Java or Groovy code block, but actually it's not the same. The code within a regular code block (whether its a method block, static block, synchronized block, or just a block of code) is executed by the virtual machine as soon as it's encountered. With closures the statements within the curly brackets are not executed until the call() is made on the closure. In the previous example the closure is declared in line, but it's not executed at that time. It will only execute if the call() is explicitly made on the closure

我在想,这是怎么回事,在Java中,如果你有一个实例方法,代码只在调用该方法时执行,那么他们怎么说上面的VM一看到它就执行?如果我有一个方法func(){int a =5; return a+5;},我的理解是只有在调用时才会执行。

4

2 回答 2

3

仅使用同步块或常规范围大括号可能会更好地进行描述。它试图表明的是,当执行线程遇到常规代码块时,它会继续执行内容。使用闭包定义,块中的代码不会立即执行 - 它用于定义/实例化包含该逻辑的闭包对象(例如,clos),稍后可以通过 clos.call() (或只是 clos( ))。

例子:

def x = 1

synchronized(this) {
    x = 1000
}
println x //x == 1000

对比

def x = 1

Closure clos = { 
    x = 1000
}
println x // x == 1
clos()  // or clos.call()
println x // x == 1000

W/R/T 方法/静态块:我不清楚是否有一些细微的方式可以在 JVM 上下文中使用“遇到”和“执行”来使语句的那一部分正确,但出于实际目的,这充其量是误导。方法仍然只在调用时执行,而不是因为它们的声明位于代码执行的明显路径中,因为可以在 groovyConsole 中运行以下内容来显示:

def x = 1

void methodA() {
    x = 1000
}

def b = {
    x = x + 1

}

println x // x is still 1
于 2012-11-04T05:07:21.360 回答
0

另一个在技术上不一定准确的类比是将闭包视为具有单个方法(闭包的主体)的匿名内部类。

执行closure.call() 或closure()(call() 的简写),调用该单一方法。

当然,闭包还有其他特性,但我认为这是思考基础知识的好方法。

于 2012-11-04T14:14:51.387 回答