Biblioteca Java - Rev 28

Subversion Repositories:
Rev:
package exemple.fire.latch;

import java.util.concurrent.*;  

/*
 * The next synchronization control is called a latch. Latching variables specify
 * conditions that once set never change. This provides a way to start several
 * threads and have them wait until a signal is received from a coordinating thread.
 * Latching works well with initialization tasks, where you want no process to run
 * until everything needed is initialized. Latching also works well for multiplayer
 * games, where you don't want any player to start until all players have joined.
 *
 * The CountDownLatch class encapsulates a latch that is initialized with a given
 * count. The constructor takes the count as its one argument. The count works in
 * a way similar to the parties argument to the CyclicBarrier constructor. It
 * indicates how many times a countDown method must be called, one for each party
 * involved. After the full count is reached, any threads waiting because of an await
 * method are released.
 *
 * The following program, LatchTest, demonstrates the use of a CountDownLatch. The
 * program creates a set of threads, but doesn't let any thread start until all the
 * threads are created.
 *
 * The main thread awaits on a second latch to make sure that the other threads are
 * finished. This example could have simply used a join operation on the created
 * threads, however imagine if you needed to synchronize threads at different phases
 * through their lifetime, instead of just at the end.
 *
 */

public class LatchTest {
  private static final int COUNT = 10;
  private static class Worker implements Runnable {
    CountDownLatch startLatch;
    CountDownLatch stopLatch;
    String name;
    Worker(CountDownLatch startLatch,
        CountDownLatch stopLatch, String name) {
      this.startLatch = startLatch;
      this.stopLatch = stopLatch;
      this.name = name;
    }
   
    public void run() {
      try {
        startLatch.await();
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      }
      System.out.println("Running: " + name);
      stopLatch.countDown();
    }
 }      
   
 public static void main(String args[]) {
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch stopSignal  = new CountDownLatch(COUNT);
    for (int i=0; i<COUNT; i++) {
      new Thread(
        new Worker(startSignal, stopSignal,
          Integer.toString(i))).start();
    }
    System.out.println("Go");
    startSignal.countDown();
    try {
      stopSignal.await();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    System.out.println("Done");
  }
}