Calling closures
In our previous examples, we were passing closures to the built-in collection methods. In the examples to date, we have deferred to the collection method to do the closure invocations for us. Let's now look at how we can make a call to the closure ourselves. For the sake of this example, we will ignore the fact that the GDK provides versions of the Thread.start
method that achieves the same thing:
class CThread extends Thread { Closure closure CThread( Closure c ) { this.closure = c this.start() } public void run() { if (closure) closure() // invoke the closure } } CThread up = new CThread( { [1..9]* each { sleep(10 * it) println it } } ) 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...