Pages

Wednesday, February 23, 2011

Java Threads Example

This is a small example of how to use Threads in Java. The code will check if a number is prime or not. You can configure the number of threads that will run. Each thread will try to divide the number to be tested  by a different number. If the number to be tested gets divided by another number, the program will print that it is not prime and also print the number that it can be divided by. This example also demonstrates the use of the "AtomicIntger" class in the "java.util.concurrent" package. If you are looking for a simpler example you can take a look at this example first and then come back and take a look at this.

public class Divisor extends Thread {

  //Will hold the number to be tested
  private int testNumber;

  //Will hold the number we will try to divide by
  private AtomicInteger nextNumber;
 
  private int sqrtOfTestNumber;

  public Divisor(AtomicInteger nextNumber, int testNumber) {   
    this.nextNumber = nextNumber;
    this.testNumber = testNumber;
    sqrtOfTestNumber = (int) Math.ceil(Math.sqrt(testNumber));
  }

  @Override
  public void run() {
    while (nextNumber.intValue() < sqrtOfTestNumber
              &&
            PrimeTester.IS_PRIME.get()) {
      if (testNumber % nextNumber.incrementAndGet() == 0) {
        PrimeTester.IS_PRIME.set(false);
        System.out.println(testNumber + " is not a prime!");
        System.out.println("It can be divided by "
                             + nextNumber.intValue() + ".");
        return;
      }
    }   
  } 
}
public class PrimeTester {

  public static AtomicBoolean IS_PRIME =
                                  new AtomicBoolean(true); 
  private AtomicInteger nextNumber = new AtomicInteger(1);
  private int numberOfThreads;
  private int testNumber;

  public PrimeTester(int numberOfThreads, int testNumber) {
    this.numberOfThreads = numberOfThreads;
    this.testNumber = testNumber;
  }

  public void test() {
    for (int i = 0; i < numberOfThreads; i++) {
      new Divisor(nextNumber, testNumber).start();
    }
  }
 
  public static void main(String[] args) {
    PrimeTester primeTester = new PrimeTester(5, 370248452);
    primeTester.test();
  }
}

Note that the program will not output anything if the number is prime. This is because additional checks have to be performed in order to do this and it will complicate the code. Since this is meant to be a simple example, it has not been included here. Maybe it can be explained in a future post.

No comments:

Post a Comment