Java Reference
In-Depth Information
for (int i = 1; i <= 3; i++) {
MeetAtBarrier t = new MeetAtBarrier(i, barrier);
t.start();
}
}
}
Thread #1 is going to work for 22 seconds
Thread #2 is going to work for 16 seconds
Thread #3 is going to work for 27 seconds
Thread #2 is waiting at the barrier...
Thread #1 is waiting at the barrier...
Thread #3 is waiting at the barrier...
We are all together. It's party time...
Thread #2 passed the barrier...
Thread #1 passed the barrier...
Thread #3 passed the barrier...
You might have noticed that inside the run() method of the MeetAtBarrier class, you are catching
BrokenBarrierException . If a thread times out or it is interrupted while waiting at the barrier point, the barrier is
considered broken. The thread that times out is released with a TimeoutException , whereas all waiting threads at the
barrier are released with a BrokenBarrierException .
Tip the await() method of the CyclicBarrier class returns the arrival index of the thread calling it. the last thread
to arrive at the barrier has an index of zero and the first has an index of the number of threads in the group minus one.
You can use this index to do any special processing in your program. For example, the last thread to arrive at the barrier
may log the time when a particular round of computation is finished by all participating threads.
Phasers
The Phaser class in the java.util.concurrent package provides an implementation for another synchronization
barrier called phaser . A Phaser provides functionality similar to the CyclicBarrier and CountDownLatch
synchronizers. However, it is more powerful and flexible. It provides the following features:
CyclicBarrier , a Phaser is also reusable.
Like a
CyclicBarrier , the number of parties to synchronize on a Phaser can change
dynamically. In a CyclicBarrier , the number of parties is fixed at the time the barrier is
created. However, in a Phaser , you can add or remove parties at any time.
Unlike a
Phaser has an associated phase number, which starts at zero. When all registered
parties arrive at a Phaser , the Phaser advances to the next phase and the phase number is
incremented by one. The maximum value of the phase number is Integer.MAX_VALUE . After
its maximum value, the phase number restarts at zero.
A
Phaser has a termination state. All synchronization methods called on a Phaser in a
termination state return immediately without waiting for an advance. The Phaser class
provides different ways to terminate a phaser.
A
 
 
Search WWH ::




Custom Search