import java.math.BigInteger; /** * Worker class used in multithreading to check, whether a given number is a prime. */ public class Worker extends Thread { private boolean isPrime; private BigInteger minVal; private BigInteger maxVal; private BigInteger candidate; private boolean finished = false; private String threadName ; public Worker(BigInteger candidate, BigInteger min, BigInteger max, String threadName) { this.minVal = min; this.maxVal = max; this.candidate = candidate; this.isPrime = true; this.threadName = threadName; //System.out.println("Created "+threadName+" for "+min+"-"+max+""); } /** * Returns a flag, indicating whether the prime candidate has a divisor in the given interval. * Since the thread might be still be running, it is important to check it first by using the * hasFinished() method. * * @return flag indicating whether there is a divisor or not */ public boolean isPrime() { return this.isPrime; } /** * Returns if the thread has finished checking the given interval. * * @return the boolean */ public boolean hasFinished() { return this.finished; } public void run() { BigInteger divCandidate = minVal; if (divCandidate.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)){ divCandidate = divCandidate.add(BigInteger.ONE); } while (divCandidate.compareTo(maxVal) < 1){ //divCandidate <= maxVal //System.out.println(this.threadName + " is testing "+divCandidate); if (candidate.mod(divCandidate).equals(BigInteger.ZERO)) { this.isPrime = false; this.finished = true; return; } divCandidate = divCandidate.add(BigInteger.ONE).add(BigInteger.ONE); } this.finished = true; // No divisor found, we are done for this interval } }