Groovy 裡常用的非同步操作方式
阿新 • • 發佈:2019-01-02
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