package developerworks.jetty6.gpstracker;
import java.util.*;
/**
* Generates a random walk
*/
public class RandomWalkGenerator implements Runnable {
private static RandomWalkGenerator instance = new RandomWalkGenerator();
private Set<CoordListener> listeners = new HashSet<CoordListener>();
private GpsCoord currentCoord;
private RandomWalkGenerator() {
currentCoord = new GpsCoord(51.517476f,-0.086603f);
new Thread(this).start();
}
public static RandomWalkGenerator getInstance() {
return instance;
}
public void run() {
try {
while (true) {
int sleepMillis = 5000 + (int)(Math.random()*8000d);
Thread.sleep(sleepMillis);
dispatchUpdate(generateNextCoord());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void addListener(CoordListener listener) {
synchronized(listeners) {
listeners.add(listener);
}
}
private void dispatchUpdate(GpsCoord coord) {
synchronized(listeners) {
for (CoordListener listener : listeners) {
listener.onCoord(coord);
}
}
}
private GpsCoord generateNextCoord() {
double dist = Math.random() * 0.002;
double angle = Math.random() * 2d * Math.PI;
float lat = currentCoord.getLatitude() + (float)(dist * Math.cos(angle));
float lng = currentCoord.getLongitude() + (float)(dist * Math.sin(angle));
currentCoord = new GpsCoord(lat,lng);
return currentCoord;
}
}
评论2