转载:https://blog.csdn.net/liubenlong007/article/details/54574878
在actor运行过程中,可能会有多种状态,各个状态间可能会存在切换的情况,akka已经帮我们考虑到这种情况情况的处理:Procedure
.
下面模拟一个婴儿。婴儿有两种不同的状态,开心和生气,婴儿有个特点就是好玩,永远不会累,所以让其睡觉婴儿就会生气,让他继续玩就会很高兴。
简单代码如下:
package akka;
import akka.actor.*;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.Procedure;
import com.typesafe.config.ConfigFactory;
/**
* Created by liubenlong on 2017/1/12.
*/
public class ProcedureTest extends UntypedActor {
private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);
Procedure
输出结果:
[INFO] [01/16/2017 15:50:53.967] [strategy-akka.actor.default-dispatcher-2] [akka://strategy/user/ProcedureTest] onReceive msg: PLAY
[INFO] [01/16/2017 15:50:54.000] [strategy-akka.actor.default-dispatcher-2] [akka://strategy/user/ProcedureTest] i am happy! SLEEP
[INFO] [01/16/2017 15:50:54.000] [strategy-akka.actor.default-dispatcher-2] [akka://strategy/user/ProcedureTest] i do not like sleep!
[INFO] [01/16/2017 15:50:54.000] [strategy-akka.actor.default-dispatcher-2] [akka://strategy/user/ProcedureTest] i am angray! PLAY
[INFO] [01/16/2017 15:50:54.000] [strategy-akka.actor.default-dispatcher-2] [akka://strategy/user/ProcedureTest] i like play.
[INFO] [01/16/2017 15:50:54.000] [strategy-akka.actor.default-dispatcher-2] [akka://strategy/user/ProcedureTest] i am happy! PLAY
[INFO] [01/16/2017 15:50:54.004] [strategy-akka.actor.default-dispatcher-2] [akka://strategy/user/ProcedureTest] i am alrady happy!!
注意:
akka.ProcedureTest#onReceive
这个方法只被调用一次,只有的切换均在procedure
中处理,所以在实际开发过程中要注意状态切换的准确性。