CS 202 - Computer Science II - Spring 2008
Threads


Loyola College > Department of Computer Science > Dr. James Glenn > CS 202 > Examples and Lecture Notes > Threads

Primes.java

/**
 * Finds prime numbers using threads.
 *
 * @author Jim Glenn
 * @version 0.1 4/7/2008
 */

public class Primes
{
    public static void main(String[] args)
    {
	// create a thread to find primes of form 4x + 1 for x >= 0

	Thread t1 = new Thread(new PrimeThread(4, 1));

	// create a thread to find primes of form 4x + 3 for x >= 0

	Thread t2 = new Thread(new PrimeThread(4, 3));

	// output primes that are not of the two forms above

	System.out.println(2);
	
	// start the threads going

	t1.start();
	t2.start();
    }

    /**
     * Determines if the given integer is prime.
     *
     * @param n an integer
     */

    public static boolean isPrime(int n)
    {
	if (n % 2 == 0 || n < 3)
	    return false;

	// search for odd factors between 3 and sqrt(n)

	int factor = 3;

	while (factor * factor <= n && n % factor > 0)
	    factor += 2;

	return (factor * factor > n);
    }

}

PrimeThread.java

/**
 * For a given even, positive integer a and a given odd, positive integer b,
 * these threads find all primes of the form ax + b for positive integers x.
 *
 * @author Jim Glenn
 * @version 0.1 4/7/2008
 */

public class PrimeThread implements Runnable
{
    private int modulus;
    private int remainder;

    public PrimeThread(int a, int b)
    {
	if (a < 0 || b < 0)
	    throw new IllegalArgumentException("Arguments must be positive: "
					       + a + " " + b);

	if (a % 2 != 0)
	    throw new IllegalArgumentException("modulus must be even: " + a);

	if (b % 2 != 1)
	    throw new IllegalArgumentException("remainder must be odd: " + b);

	
	modulus = a;
	remainder = b;
    }

    public void run()
    {
	// compute the first integer to check
	
	int cand = remainder;
	
	// loop until arithmetic overflow
	
	while (cand > 0)
	    {
		// report tested number if it is prime

		if (Primes.isPrime(cand))
		    System.out.println(cand);

		// go to next integer to test

		cand += modulus;
	    }
    }
}
This code can also be downloaded from the files
Primes.java, and PrimeThread.java.