package waitnotify;

import java.util.Queue;

/**
 * @author ssb
 */
public class PrimeProducer implements Runnable {

	private int low_, high_;
	private Queue<Integer> primes_;
	private volatile boolean shutdown_;

	/**
	 * @param low
	 * @param high
	 * @param primes
	 */
	public PrimeProducer ( int low, int high, Queue<Integer> primes ) {
		super();
		low_ = low;
		high_ = high;
		primes_ = primes;
		shutdown_ = false;
	}

	public void shutdown () {
		shutdown_ = true;
	}

	/*
	 * (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run () {
		for ( int num = low_ ; num < high_ && !shutdown_ ; num++ ) {
			if ( isPrime(num) ) {
				System.out.println("producing " + num);
				synchronized ( primes_ ) {
					primes_.add(num);
					primes_.notify();
				}
				try {
					Thread.sleep((long) (Math.random() * 2000)+2000);
				} catch ( InterruptedException e ) {}
			}
		}
	}

	public boolean isPrime ( int number ) {
		if ( number <= 1 ) {
			return false;
		}
		for ( int div = 2 ; div < number ; div++ ) {
			if ( number % div == 0 ) {
				return false;
			}
		}
		return true;
	}

}
