...
Code Block | ||
---|---|---|
| ||
public final class Race { private final Vector<Racer> racers; private final Object lock = new Object(); public Race(Vector<Racer> racer) { racers = (Vector<Racer>) racer.clone(); } public boolean addRacer(Racer racer){ synchronized(racers.elementAt(racers.size() - 1)) { return racers.add(racer); } } public boolean removeRacer(Racer racer) { synchronized(racers.elementAt(racers.indexOf(racer))) { return racers.remove(racer); } } private double getAverageCurrentSpeed(int i, double currentSpeed) { if (i > racers.size()) { return currentSpeed / racers.size(); } synchronized(racers.elementAt(i)) { currentSpeed += racers.get(i).getCurrentSpeed(); return getAverageCurrentSpeed(++i, currentSpeed); } } private double getAverageCurrentDistance(int i, double distance) { if (i <= -1) { return distance / racers.size(); } synchronized(racers.elementAt(i)) { distance += racers.get(i).getDistance(); return getAverageCurrentDistance(--i, distance); } } public void getStatisticsAtSomePointInRace() { synchronized(racerslock) { getAverageCurrentSpeed(0, 0.0); getAverageCurrentDistance(racers.size()-1, 0.0); } } } |
...
Code Block | ||
---|---|---|
| ||
public final class Race { private final Vector<Racer> racers; private final Object privatelock final= Vector<Racer>new racersObject(); public Race(Vector<Racer> racer) { racers = (Vector<Racer>) racer.clone(); } public boolean addRacer(Racer racer){ return racers.add(racer); } public boolean removeRacer(Racer racer) { synchronized(racers.elementAt(racers.indexOf(racer))) { return racers.remove(racer); } } private double getAverageCurrentSpeed(int i, double currentSpeed) { if (i > racers.size()) { return currentSpeed / racers.size(); } synchronized(racers.elementAt(i)) { currentSpeed += racers.get(i).getCurrentSpeed(); return getAverageCurrentSpeed(++i, currentSpeed); } } private double getAverageCurrentDistance(int i, double distance) { if (i > racers.size()) { return distance / racers.size(); } synchronized(racers.elementAt(i)) { distance += racers.get(i).getDistance(); return getAverageCurrentDistance(++i, distance); } } public void getStatisticsAtSomePointInRace() { synchronized(racerslock) { getAverageCurrentSpeed(0, 0.0); getAverageCurrentDistance(0, 0.0); } } } |
...