import java.awt.*; import java.util.Arrays; import javax.swing.JTextArea; class Calculate extends Thread { public static final int RUNNING = 0; public static final int PAUSED = 1; public static final int STOPPED = 2; private int status = STOPPED; private JTextArea textArea; private static final int MAX_PRIMES = 10000; int primesSaved = 0; long[] referencePrimes = new long[MAX_PRIMES]; // primes to check against long[] squaredPrimes = new long[MAX_PRIMES];// reference primes squared public Calculate(JTextArea ta) { textArea = ta; } public void pause() { status = PAUSED; } public void stopRunning() { status = STOPPED; } public void continueRunning() { status = RUNNING; } public int getStatus() { return status; } private void init() { status = RUNNING; Arrays.fill(referencePrimes, 0l); Arrays.fill(squaredPrimes, 0l); referencePrimes[0] = 3; // store initial prime squaredPrimes[0] = 9; textArea.append("2\n"); // don't have to verify textArea.append("3\n"); } public void run() { init(); long testValue = 5; // first number to test while (testValue < squaredPrimes[primesSaved] && status == RUNNING) { if (isPrime(testValue)) { textArea.append(testValue + "\n"); textArea.setCaretPosition(textArea.getText().length()-1); if (primesSaved < MAX_PRIMES - 1) { referencePrimes[++primesSaved] = testValue; // save prime squaredPrimes[primesSaved] = testValue * testValue; } } testValue += 2; Thread.yield();//be nice while (status == PAUSED) { try { sleep(200); } catch (InterruptedException ie) { } } if ((testValue - 1) % 200000l == 0) textArea.setText(""); } textArea.append("Stopped.\n\n"); status = STOPPED; } private boolean isPrime(long x) { int index = 0; while (index <= primesSaved && x >= squaredPrimes[index]) { if (x % referencePrimes[index] == 0) return false; else index++; } return true; } }