java,并发,执行器

时间:2014-04-23 23:54:25

标签: java concurrency

我有一个简单的类,它使用ExecutorService并使用蒙特卡罗方法计算PI。

  public class MonteCarlo {
public static void main(String[] args) throws ExecutionException, InterruptedException {

    long start = System.currentTimeMillis();

    ExecutorService executorService = Executors.newFixedThreadPool(2);

    long numberOfWorkers = 1000000;
    double x = 0.0;
    double y = 0.0;
    double radius = 5.0;
    long numberOfAllShoots = 0;

    Set<Future<Integer>> futures = new HashSet<>();
    for(int i=0;i<numberOfWorkers;i++) {
        long shootNumber = 500;
        numberOfAllShoots+=shootNumber;
        Callable callable = new Shoot(x,y,radius,shootNumber);
        Future<Integer> future = executorService.submit(callable);
        futures.add(future);
    }

    int numberOfCorrectShoots = 0;
    for (Future<Integer> future : futures) {
        numberOfCorrectShoots += future.get();
    }
    executorService.shutdown();

    double pi = 4 * ((double)numberOfCorrectShoots / numberOfAllShoots );

    System.out.printf("PI is approximated to " + pi);

    long end = System.currentTimeMillis();

    System.out.println("\n"+(end - start) + " miliseconds ");

}

}

但问题是当我将newFixedThreadPool参数设置为100或2时,我的运行时间几乎相同。使用newSingleThreadExecutor的结果相同。 这段代码有什么问题?我期望使用newFixedThreadPool会比单线程

快得多

修改

拍摄课程

   public class Shoot implements Callable {

private final double x;
private final double y;
private final double radius;
private final long numberOfShoots;

public Shoot(double x, double y, double radius, long numberOfShoots) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.numberOfShoots = numberOfShoots;
}

@Override
public Integer call() {
    int numberOfCorrectShoot = 0;
    for(int i=0;i<numberOfShoots;i++) {
        double t = randomDoubleFromRange(x-radius,x+radius);
        double u = randomDoubleFromRange(y-radius,y+radius);
        if((x-t)*(x-t) + (y-u)*(y-u) <= radius * radius) {
            numberOfCorrectShoot++;
        }
    }
    return numberOfCorrectShoot;
}

private double randomDoubleFromRange(double rangeMin, double rangeMax) {
    Random random = new Random();
    return rangeMin + (rangeMax - rangeMin) * random.nextDouble();
}

}

nproc命令返回2

我尝试过numberOfWorkers = 400和shootNumber = 1000000,newSingleThreadExecutor和newSingleThreadExecutor(2)或更多都给出了大约51000毫秒的结果

0 个答案:

没有答案