View Javadoc
1   package ch.hslu.exercises.sw08.ex1;
2   
3   import java.math.BigInteger;
4   import java.util.Random;
5   import java.util.concurrent.ExecutorService;
6   import java.util.concurrent.Executors;
7   
8   public final class PrimeCalculator {
9   
10  
11      private final int threads;
12  
13      public PrimeCalculator(final int threads) {
14          this.threads = threads;
15      }
16  
17      public void calculatePrimesConcurrent() {
18          try (ExecutorService executor = Executors.newFixedThreadPool(threads)) {
19              for (int i = 0; i < 100; i++) {
20                  executor.execute(new PrimeSearcher());
21              }
22          }
23      }
24  
25      public void calculatePrimesSingleThreaded() {
26          int n = 1;
27          while (n <= 100) {
28              BigInteger bi = new BigInteger(1024, new Random());
29              if (bi.isProbablePrime(Integer.MAX_VALUE)) {
30                  n++;
31              }
32          }
33      }
34  
35  
36      private static final class PrimeSearcher implements Runnable {
37          @Override
38          public void run() {
39              while (true) {
40                  BigInteger bi = new BigInteger(1024, new Random());
41                  if (bi.isProbablePrime(Integer.MAX_VALUE)) {
42                      return;
43                  }
44              }
45          }
46      }
47  }