// Using threads for testing primality. Modified from Peter van der Linde, // "Just Java" 4th edition, Sun Microsystems Press, Prentice Hall, 1999, // pp. 268-9 // Tests for primality by dividing the range of possible factors into intervals // of size RangeSize and using a separate thread for each such range. class testRange extends Thread { int from, Num, to; // constructor testRange(int argFrom, int argNum) { Num = argNum; if (argFrom == 0) from = 2; else from = argFrom; to = argFrom + testPrime.RangeSize; } public void run() { for (int i=from; i< to && i < Num; i++) { if (Num%i == 0) { System.out.println("factor " + i + " found by thread " + getName()); this.yield(); // yield to another thread if you've found a solution } } } } // end testRange public class testPrime { public static final int RangeSize = 100; public static void main (String s[]) { int Num = Integer.parseInt(s[0]); int nThreads = (Num/RangeSize)+1; for (int i=0; i < nThreads; i++) { new testRange(i*100,Num).start(); } } }