Chapter 5
[ 93 ]
}
} )
CThread down = new CThread(
{
["three","two", "one", "liftoff"] each {
sleep(100)
println it
}
} )
Here we define a subclass of the Java Thread class, which can be constructed with
a closure. The run method of the Thread invokes the closure using an unnamed ()
invocation on the closure field. The CThread constructor automatically starts the
thread. We can invoke a closure in two different ways, as follows:
- Using the unnamed () invocation syntax, as described here:
public void run(Closure closure) {
closure()
} - By calling the call() method of groovy.lang.Closure, as follows:
public void run(Closure closure) {
closure.call()
}
This example was useful as an illustration of how to call a closure that you have
saved in a member field or variable. However, I think you will agree that the built-in
Thread.start method taking a closure is far more elegant:
Thread.start
{
[1..9]*.each {
sleep(10 * i)
println i
}
}
Thread.start
{
["three","two", "one", "liftoff"] .each {
sleep(100)
println i
}
}