本文概述
- Akka终止顶级Actor示例
- Akka终止子Actor的例子
- Akka Stopping ActorSystem示例
actor的实际终止是异步执行的。
Akka中还有其他一些方法可以用来终止Actor。其中一些是PoisonPill, terminate()和gracefulStop()用于终止Actor。
Akka终止顶级Actor示例你只需调用stop()方法即可终止顶级Actor。以下示例描述了stop()方法的用法。
import akka.actor.{Actor, ActorSystem, Props};
class ActorExample extends Actor{
def receive = {
case message:String =>
println("Message received: "+message);
case _ =>
println("Unknown message");
}
override def postStop(){
println("Actor stoped");
}
}object ActorExample{
def main(args:Array[String]){
val actorSystem = ActorSystem("ActorSystem");
val actor = actorSystem.actorOf(Props[ActorExample], "RootActor");
actor ! "Hello"
actorSystem.stop(actor);
}
}
输出
Message received: Hello
Actor stoped
Akka终止子Actor的例子
import akka.actor.{Actor, ActorSystem, Props};
class ActorExample extends Actor{
def receive = {
case message:String =>
println("Message received by "+self.path.name+": "+message);
val childactor = context.actorOf(Props[ChildActor], "ChildActor");
childactor ! "Hello child Actor"
context.stop(childactor);
case _ =>
println("Unknown message");
}
}class ChildActor extends Actor{
def receive = {
case message:String =>
println("Message received by "+self.path.name+": "+message);
case _ =>
println("Unknown message");
}override def postStop(){
println("Child Actor stoped");
}
}object ActorExample{
def main(args:Array[String]){
val actorSystem = ActorSystem("ActorSystem");
val actor = actorSystem.actorOf(Props[ActorExample], "RootActor");
actor ! "Hello"}
}
输出
Message received by RootActor: Hello
Message received by ChildActor: Hello child Actor
Child Actor stoped
Akka Stopping ActorSystem示例你可以通过调用actor的终止方法来终止它。此方法将终止守护者actor, 而后者又将递归终止其所有子actor。
import akka.actor.{Actor, ActorSystem, Props};
class ActorExample extends Actor{
def receive = {
case message:String =>
println("Message received by "+self.path.name+": "+message);
val childactor = context.actorOf(Props[ChildActor], "ChildActor");
childactor ! "Hello child Actor"
case _ =>
println("Unknown message");
}override def postStop(){
println("Top Level Actor stoped");
}
}class ChildActor extends Actor{
def receive = {
case message:String =>
println("Message received by "+self.path.name+": "+message);
case _ =>
println("Unknown message");
}override def postStop(){
println("Child Actor stoped");
}
}object ActorExample{
def main(args:Array[String]){
val actorSystem = ActorSystem("ActorSystem");
val actor = actorSystem.actorOf(Props[ActorExample], "RootActor");
actor ! "Hello"
actorSystem.terminate();
}
}
输出
Message received by RootActor: Hello
Message received by ChildActor: Hello child Actor
Child Actor stoped
Top Level Actor stoped
推荐阅读
- Akka ActorSystem组件用法示例
- Akka Props用法示例详解
- Akka子Actor用法示例
- Akka Actor生命周期解释和示例详解
- Akka Actor发送消息示例详解
- Hbuilder X在Android app开发上真机调试的使用
- Android File存储:文件读写
- Android File存储(文件的存储路径)
- ORM框架--Dapper