gpt4 book ai didi

java - 从 Java 多线程到 Scala Akka actor

转载 作者:行者123 更新时间:2023-12-02 05:30:37 25 4
gpt4 key购买 nike

我是 Scala 新手,所以我需要帮助。我有一个用 Java 完成的示例,我必须使用 Scala 创建同样的东西。例子是这样的:

import java.util.ArrayList;

public class Z
{
public static void main(String[] args)
{
A a=new A();
B b=new B(a);
a.setB(b);
a.addMessage("A1");
a.addMessage("A2");
a.addMessage("A3");
b.addMessage("B1");
b.addMessage("B2");
b.addMessage("B3");
b.addMessage("B4");
a.start();
b.start();
}
}

class A extends Thread
{
ArrayList<String> msgs=new ArrayList<String>();
B b;

public void setB(B tb)
{
b=tb;
}

public void run() //It's like a send() method
{
for (int i=0; i<msgs.size(); i++)
{
final String msg=msgs.get(i);
new Thread()
{
public void run()
{
b.receive(msg);
}
}.start();
}
}

public void receive (String msg)
{
System.out.println("A received a message from B.");
}

public void addMessage(String message)
{
msgs.add(message);
}
}

class B extends Thread
{
ArrayList<String> msgs=new ArrayList<String>();
A a;

public B(A ta)
{
a=ta;
}

public void run() //It's like a send() method
{
for (int i=0; i<msgs.size(); i++)
{
final String msg=msgs.get(i);
new Thread()
{
public void run()
{
a.receive(msg);
}
}.start();
}
}

public void receive (String msg)
{
System.out.println("B received a message from A.");
}

public void addMessage(String message)
{
msgs.add(message);
}
}

两个 Actor 的创建类似,但问题出在 run() 上。我知道我可以使用这样的东西

receive
{
case msg=>println("A received a message from B.");
}

在两个 act() 中接收消息(我必须说这非常有用),但我不知道如何重新创建发送消息的部分。我应该在 main 中启动 actor,然后在 act() 之外发送消息吗?

最佳答案

考虑以下 Akka Actor 的实现。请注意

  • 这里的 run 方法被替换为 SendAll 消息;
  • 通过将此类引用添加到SendAll,可以简化参与者之间传递的参与者引用;
  • 代码简洁性的一个小改进是将每条文本消息封装到一个列表中;
  • 参与者日志系统取代了 println

因此,

import akka.actor.{ActorSystem, Props, Actor, ActorRef, ActorLogging}
import collection.mutable.ListBuffer

sealed trait Messaging
case class Add(msgs: List[String]) extends Messaging
case class Receive(msgs: String) extends Messaging
case class SendAll(dest: ActorRef) extends Messaging


class Messenger extends Actor with ActorLogging {
var messages = new ListBuffer[String]()

def receive = {
case Add(msgs) => messages ++= msgs
case Receive(msg) => log.info(s"received $msg from ${sender.path}.")
case SendAll(dest) => messages.foreach(dest ! Receive(_))
}
}

object Main extends App {

val system = ActorSystem("MessengerSystem")
val aActor = system.actorOf(Props[Messenger], name = "aActor")
val bActor = system.actorOf(Props[Messenger], name = "bActor")

aActor ! Add(List("A1","A2","A3"))
bActor ! Add(List("B1","B2","B3","B4"))

aActor ! SendAll(bActor)
bActor ! SendAll(aActor)

system.shutdown
}

关于java - 从 Java 多线程到 Scala Akka actor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25582494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com