Home > Articles

  • Print
  • + Share This

Starting and Stopping

To start the race, and ultimately to stop it, we'll use a java.util.concurrent class called CountDownLatch, which allows you to queue up a number of threads and start them all at once. You create a CountDownLatch with an integer count and decrement it by calling countDown(). A thread that calls await() on a CountDownLatch will sleep until the count gets to zero, and then continue on its merry way.

Our example includes two CountDownLatch instances: a greenFlag that starts the race and a checkeredFlag that each Racer decrements when it crosses the finish line for the final time. Here's how we handle that setup in the run() method for the Racer class:

public void run()
  SectorTime   sectorTime = null;
  int       currLap   = 0;

    System.out.println("Racer " + getName() + " starting!");
      for(int sector = 0; sector < getEvent().getStatus().NUM_SECTORS; ++sector)
        Thread.sleep((long)(100+ (Math.random() * 50)));
        sectorTime =
          new SectorTime(this, currLap, sector);
        getEvent().getStatus().addTimeToSectorQueue(sector, sectorTime);
  }  catch(Exception e){}

This method waits for the green flag to be dropped; then it starts posting times, sleeping some amount of time between sectors to simulate the time spent driving from sector to sector. When the race has been completed by the leader, the loop ends, and the checkered flag count is decremented. Assuming that you created the green flag with a count of 1, starting all the Racers at once is this easy:

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.