package class6_1_MultithreadPrimeAppJava_start; /* * Created by yoder on 4/30/2015. * Modified every year... */ import java.util.ArrayList; import java.util.List; /** * This worker class creates a worker thread that works on finding prime numbers. */ public class PrimeFinder { private PrimeApp primeApp; private Thread worker; private List primes = new ArrayList<>(); public PrimeFinder(PrimeApp primeApp) { this.primeApp = primeApp; } public void findPrimes() { worker = new Thread(()-> { for (long candidate = 100000000; candidate < Long.MAX_VALUE && !worker.isInterrupted(); candidate++) { if (isPrime(candidate)) { primes.add(candidate); String text = "Latest prime: " + candidate; primeApp.setRecentPrime(text); System.out.println(text); System.out.println("worker.isInterrupted() = " + worker.isInterrupted()); } } }); worker.start(); } /** * Slow O((2^b)) or worse algorithm (where b is the number of bits in candidate) * * TODO: Implement Miller-Rabin Primality test to get O(n^12) or better performance. * http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test * (Why nine characters for one dash? * Unicode character Oct Dec Hex HTML * en dash 020023 8211 0x2013 – ) * * @param candidate candidate to test * @return true if candidate is prime. */ private boolean isPrime(long candidate) { boolean isPrime = true; for(int divisor = 2; divisor < candidate && isPrime; divisor++) { if(candidate % divisor == 0) { isPrime = false; } } return isPrime; } public void interrupt() { if(worker == null) { System.err.println("Cannot stop finding primes. worker variable is null."); } else { worker.interrupt(); } } }