Pages

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

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.

Saturday, February 12, 2011

Sorting a HashMap in Java

First of all I have to point out that a HashMap can not be in a "sorted" state. This is because a HashMap does not have an order. On the other hand a TreeMap does have an order (it implements the interface SortedMap). So to sort a HashMap by key, you can use the code below.

Map sortedMap = new TreeMap(yourOriginalMap);

This will sort the map according to the keys' natural order.


In order to sort the HashMap based on the values, we have to pass a Comparator to the constructor of TreeMap. For this example let us assume that the values of the HashMap that you need to sort are Integers. Then the comparator would look like the following.


public class MyComparator implements Comparator<Object> {

    Map theMapToSort;

    public MyComparator(Map theMapToSort) {
        this.theMapToSort = theMapToSort;
    }

    public int compare(Object key1, Object key2) {
        Integer val1 = (Integer) theMapToSort.get(key1);
        Integer val2 = (Integer) theMapToSort.get(key2);
        if (val1 < val2) {
            return -1;
        } else {
            return 1;
        }
    }
}

Then you can sort the map using the following code

MyComparator comp = new MyComparator(originalMap);
TreeMap treeMap = new TreeMap(comp);
treeMap.putAll(originalMap);


Now the treeMap object will contain the values in the orginalMap, sorted by the values.