A Threaded Application to find prime number - Java Thread

Java examples for Thread:Thread Operation

Description

A Threaded Application to find prime number

Demo Code

class PrimeFinder implements Runnable {
  public long target;
  public long prime;
  public boolean finished = false;
  private Thread runner;

  PrimeFinder(long inTarget) {
    target = inTarget;/*from   w w w  .  j av a2 s .c om*/
    if (runner == null) {
      runner = new Thread(this);
      runner.start();
    }
  }

  public void run() {
    long numPrimes = 0;
    long candidate = 2;
    while (numPrimes < target) {
      if (isPrime(candidate)) {
        numPrimes++;
        prime = candidate;
      }
      candidate++;
    }
    finished = true;
  }

  boolean isPrime(long checkNumber) {
    double root = Math.sqrt(checkNumber);
    for (int i = 2; i <= root; i++) {
      if (checkNumber % i == 0)
        return false;
    }
    return true;
  }
}

public class Main {
  public static void main(String[] a) {

    long[] arguments = new long[]{3,4,6,70};
    
    PrimeFinder[] finder = new PrimeFinder[arguments.length];
    for (int i = 0; i < arguments.length; i++) {
      try {
        long count = arguments[i];
        finder[i] = new PrimeFinder(count);
        System.out.println("Looking for prime " + count);
      } catch (NumberFormatException nfe) {
        System.out.println("Error: " + nfe.getMessage());
      }
    }
    boolean complete = false;
    while (!complete) {
      complete = true;
      for (int j = 0; j < finder.length; j++) {
        if (finder[j] == null)
          continue;
        if (!finder[j].finished) {
          complete = false;
        } else {
          System.out.println("Prime " + finder[j].target + " is " + finder[j].prime);
          finder[j] = null;
        }
      }
    }
  }
}

Related Tutorials