PrimeCalculator.java

package ch.hslu.exercises.sw08.ex1;

import java.math.BigInteger;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class PrimeCalculator {


    private final int threads;

    public PrimeCalculator(final int threads) {
        this.threads = threads;
    }

    public void calculatePrimesConcurrent() {
        try (ExecutorService executor = Executors.newFixedThreadPool(threads)) {
            for (int i = 0; i < 100; i++) {
                executor.execute(new PrimeSearcher());
            }
        }
    }

    public void calculatePrimesSingleThreaded() {
        int n = 1;
        while (n <= 100) {
            BigInteger bi = new BigInteger(1024, new Random());
            if (bi.isProbablePrime(Integer.MAX_VALUE)) {
                n++;
            }
        }
    }


    private static final class PrimeSearcher implements Runnable {
        @Override
        public void run() {
            while (true) {
                BigInteger bi = new BigInteger(1024, new Random());
                if (bi.isProbablePrime(Integer.MAX_VALUE)) {
                    return;
                }
            }
        }
    }
}