Scala Actors:是否有内置方法来停止/中断 Actor?

发布于 2024-12-15 05:24:14 字数 487 浏览 3 评论 0原文

在Java中,我对线程有兴趣,例如:

Thread thread = new Thread() {

  @Override
  public void run() {
    //use this while loop, I can stop/ interrupt the thread when I want
    while (!isInterrupted()) {
      //...
    }
  }
};
thread.start();

然后,当我想停止/中断我的线程时:

thread.interrupt();

所以我的问题是:Scala中是否有内置方法(字段/方法/函数...)我可以阻止/打断演员吗?

这是我的背景:我是 Scala 新手,我正在真正学习编码。我正在寻找演员和线索之间的最佳方式。从我的角度来看,我喜欢新的方式——演员。

PS:对不起我的英语...

In Java I have a hobby with thread, for example:

Thread thread = new Thread() {

  @Override
  public void run() {
    //use this while loop, I can stop/ interrupt the thread when I want
    while (!isInterrupted()) {
      //...
    }
  }
};
thread.start();

and then, when I want to stop/ interrupt my thread:

thread.interrupt();

So my question is: is there a built-in way (a field/ method/ function...) in Scala that I can stop/ interrupt an actor?

This is my background: I'm new to Scala, I'm really learning to code. And I'm finding my best way between actor and thread. From my point of view, I like the new approach - actor.

P.S: Sorry for my English...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

相守太难 2024-12-22 05:24:14

正如另一个答案所示,Actor 模型专门设计用于将与 Actor 的所有交互限制为消息传递和处理。 Scala/Akka 通过强制您通过调用 actorOf 方法来创建 Actor 来实现此目的。由于您没有对基础对象的引用,因此无法直接调用它的方法。

因此,如果您想要一个可以被中断的 Actor,只需处理一些可以中断的消息即可。

def receive = {
  case 'Interrupt => // handle interruption...
}

并在您的客户端代码中

a ! 'Interrupt

As indicated by the other answer, the actor model is specifically designed to restrict all interaction with an Actor to message passing and handling. Scala/Akka accomplish this by forcing you to create an Actor by calling the actorOf method. Since you don't have a reference to the underlying object, you can't call methods on it directly.

So, if you want to have an Actor that can be interrupted, just handle some message that does that.

def receive = {
  case 'Interrupt => // handle interruption...
}

and in your client code

a ! 'Interrupt
屋顶上的小猫咪 2024-12-22 05:24:14

您可以向 Actor 发送 PoisonPill 来要求他终止(请参阅 http://akka.io/docs/akka/1.2/intro/getting-started-first-scala.html

请注意,这适用于 akka Actors。不知道scala演员。

You can send an Actor a PoisonPill to ask him to terminates (see http://akka.io/docs/akka/1.2/intro/getting-started-first-scala.html)

Please note that that works with akka Actors. Don't know for scala actors.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文