import element.*; public class SieveThread extends Thread { private static final int max = 10000; // largest prime reported private int fact; // factor we are sieve for private SieveThread nextSieve; // reference to next sieve private boolean inputValid; private int input; public SieveThread() { inputValid = false; // the input buffer isn't being used...yet } synchronized public int receive() // post: read a value from smaller SieveThread { while (!inputValid) { try { wait(); } catch (Exception e) { System.exit(0); } } inputValid = false; // at return, input will be gobbled notify(); // wake up possible waiting sender return input; // return soon-to-be invalid input } synchronized public void send(int n) // post: write n to larger SieveThread { while (inputValid) { try { wait(); } catch (Exception e) { System.exit(0); } } input = n; // we have the lock, set buffer inputValid = true; // indicate that the buffer is useful notify(); // wake up receiver (if waiting) } public void run() { fact = receive(); System.out.println(fact); int n; // start up next sieve in line nextSieve = new SieveThread(); nextSieve.setPriority(Thread.NORM_PRIORITY-1); nextSieve.start(); for (n = receive(); n < max; n = receive()) { // read values and pass along ones that we don't divide if (0 != n % fact) { nextSieve.send(n); } } } public static void main(String args[]) { // start up a sieve SieveThread source = new SieveThread(); source.setPriority(Thread.NORM_PRIORITY-1); source.start(); int i; for (i = 2; i < max; i++) { // send it a stream of integers source.send(i); } } }