0

Akka 入門チュートリアルを Scala から Java に変換し、アクターをスレッドに置き換えてみました。

チュートリアルはここにありますhttp://typesafe.com/resources/tutorials/getting-started-with-akka-scala.html

元の Pi.scala ファイルは、Typesafe giter8 テンプレート リポジトリからチェックアウトできます。

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();
    }
}
4

1 に答える 1