gpt4 book ai didi

java - 从 Scala 到 Java 多线程的 Akka actor 教程

转载 作者:行者123 更新时间:2023-12-01 17:24:33 25 4
gpt4 key购买 nike

我尝试将 Akka 入门教程从 Scala 转换为 Java,并用线程替换 actor。

可以在此处找到教程 http://typesafe.com/resources/tutorials/getting-started-with-akka-scala.html

原始的 Pi.scala 文件可以从 Typesafe giter8 模板存储库中 check out

g8 typesafehub/akka-first-tutorial-scala

我想知道我的做法是否正确。

这是我的 Pi.java

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Pi {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Listener listener = new Listener();

//calculate(nrOfWorkers = 10, nrOfElements = 10000, nrOfMessages = 10000)
Master master = new Master(4, 1000, 1000, listener);
master.calculate();
}
}

class Worker implements Callable<Double> {

private int start;
private int nrOfElements;

public Worker(int start, int nrOfElements) {
this.start = start;
this.nrOfElements = nrOfElements;
}

@Override
public Double call() throws Exception {
double acc = 0.0;

for(int i = start; i < start + nrOfElements; i++) {
acc += 4.0 * (1 - (i % 2) * 2) / (2 * i + 1);
}
return acc;
}
}

class Listener {

public void PiApproximation(double pi, long duration) {
System.out.println(String.format("\n\tPi approximation: \t\t%s\n\tCalculation time: \t%s", pi, duration));
}

}

class Master {

private double pi = 0.0;
private int nrOfResults = 0;
private final long start = java.lang.System.currentTimeMillis();

private int nrOfWorkers;
private int nrOfMessages;
private int nrOfElements;
private Listener listener;

private ExecutorService executor;

public Master(int nrOfWorkers,
int nrOfMessages,
int nrOfElements,
Listener listener) {

this.nrOfWorkers = nrOfWorkers;
this.nrOfMessages = nrOfMessages;
this.nrOfElements = nrOfElements;
this.listener = listener;

//Round robin scheduling is not enforced here as in akka.
executor = Executors.newFixedThreadPool(nrOfWorkers);
}

public void calculate() {
List<Future<Double>> list = new ArrayList<Future<Double>>();

for (int i = 0; i < nrOfMessages; i++) {
Callable<Double> worker = new Worker(i * nrOfElements, nrOfElements);
Future<Double> submit = executor.submit(worker);
list.add(submit);
}

for (Future<Double> future : list) {
try {
pi += future.get();
}
catch (InterruptedException e) { e.printStackTrace(); }
catch (ExecutionException e) { e.printStackTrace(); }
}
//send results to listener
listener.PiApproximation(pi, java.lang.System.currentTimeMillis() - start);

executor.shutdown();
}
}

最佳答案

网上还有本教程的 java 版本: http://doc.akka.io/docs/akka/2.0.1/intro/getting-started-first-java.html

但是,它不是使用线程,而是使用 java 中的 Actor。为什么要使用线程而不是 Actor?

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

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