(快速参考)

使用工厂方法创建 actor

import static groovyx.gpars.actor.Actors.actor

def console = actor { loop { react { println it } }

子类化 DefaultActor

class CustomActor extends DefaultActor {
    @Override protected void act() {
        loop {
            react {
                println it
            }
        }
    }
}

def console=new CustomActor() console.start()

发送消息

console.send('Message')
console << 'Message'
console.sendAndContinue 'Message', {reply -> println "I received reply: $reply"}
console.sendAndWait 'Message'

超时

import static groovyx.gpars.actor.Actors.actor

def me = actor { friend.send('Hi') react(30.seconds) {msg -> if (msg == Actor.TIMEOUT) { friend.send('I see, busy as usual. Never mind.') stop() } else { //continue conversation } } }

me.join()

当等待消息超时时,将收到 Actor.TIMEOUT 消息。如果 actor 上存在 onTimeout() 处理程序,也会调用该处理程序。

import static groovyx.gpars.actor.Actors.actor

def me = actor { delegate.metaClass.onTimeout = {-> friend.send('I see, busy as usual. Never mind.') stop() }

friend.send('Hi') react(30.seconds) { //continue conversation } }

me.join()

actor 组

def coreActors = new NonDaemonPGroup(5)  //5 non-daemon threads pool
def helperActors = new DefaultPGroup(1)  //1 daemon thread pool

def priceCalculator = coreActors.actor { … }

def paymentProcessor = coreActors.actor { … }

def emailNotifier = helperActors.actor { … }

def cleanupActor = helperActors.actor { … }

//increase size of the core actor group coreActors.resize 6

//shutdown the group's pool once you no longer need the group to release resources helperActors.shutdown()

DynamicDispatchActor

final Actor actor = new DynamicDispatchActor({
    when {String msg -> println 'A String'; reply 'Thanks'}
    when {Double msg -> println 'A Double'; reply 'Thanks'}
    when {msg -> println 'A something ...'; reply 'What was that?'}
})
actor.start()

反应器

import groovyx.gpars.actor.Actors

final def doubler = Actors.reactor { 2 * it }.start()