Groovy中三种异步运行代码的方式
A. 传统的线程方式 Thread
def mytask={println "3.hello"}
println "1.begin"
new Thread( {
mytask();
}).start()
println "2.end"
将会输出:
1.begin 2.end 3.hello
B. 使用事件发送订阅模型 Events
import grails.events.Events
@Consumer
class Game implements Events{
@Selector("play")
def doPlay(Object msg) {
println msg.toString()
}
}
def gameScenarioService
//send event,will call doPlay method asyncrhonously
notify ( "play","First Play" )
C. 使用并行库 GPars
@Grab(group='org.codehaus.gpars',module='gpars',version='1.2.1')
import groovyx.gpars.actor.DefaultActor
class CustomActor extends DefaultActor {
@Override protected void act() {
loop {
react {
println it
}
}
}
}
println "begin"
def console=new CustomActor()
console.start()
//trigger to react
console.send('Message')
println "end"
sleep(100) {
// wait Message
}
将会输出:
begin end Message