Java Reference
In-Depth Information
// Add the integer to the list
list.add(num);
// Wait for all parties to arrive at the phaser
phaser.arriveAndAwaitAdvance();
}
while (!phaser.isTerminated());
}
}
Listing 6-40 creates a
Phaser
by inheriting an anonymous class from the
Phaser
class. In its
onAdvance()
method,
it terminates the phaser after the second advance, which is controlled by the
PHASE_COUNT
constant, or if the registered
parties reduces to zero. You use a synchronized
List
to gather the random integers generated by the adder tasks.
You plan to use three adder tasks, so you register four parties (one more than the number of tasks) with the phaser.
The additional party will be used to synchronize each phase. It waits for each phase advance until the
Phaser
is
terminated. At the end, sum of the random integers generated by all adder tasks is computed and displayed on the
standard output.
Listing 6-40.
A Program to Use Multiple AdderTask Tasks with a Phaser
// AdderTaskTest.java
package com.jdojo.threads;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.Phaser;
public class AdderTaskTest {
public static void main(String[] args) {
final int PHASE_COUNT = 2;
Phaser phaser
= new Phaser() {
public boolean onAdvance(int phase, int parties) {
// Print the phaser details
System.out.println("Phase:" + phase
+ ", Parties:" + parties
+ ", Arrived:" + this.getArrivedParties());
boolean terminatePhaser = false;
// Terminate the phaser when we reach the PHASE_COUNT
// or there is no registered party
if (phase >=PHASE_COUNT - 1 || parties == 0) {
terminatePhaser = true;
}
return terminatePhaser;
}
};