Java Reference
In-Depth Information
// Use a synchronized List
List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>());
// Let's start three tasks
final int ADDER_COUNT = 3;
// Register parties one more than the number of adder tasks.
// The extra party will synchronize to compute the result of
// all generated integers by all adder tasks
phaser.bulkRegister(ADDER_COUNT + 1);
for (int i = 1; i <= ADDER_COUNT; i++) {
// Create the task and start it
String taskName = "Task #" + i;
AdderTask task = new AdderTask(taskName, phaser, list);
task.start();
}
// Wait for the phaser to terminate, so we can compute the sum
// of all generated integers by the adder tasks
while (!phaser.isTerminated()) {
phaser.arriveAndAwaitAdvance();
}
// Phaser is terminated now. Compute the sum
int sum = 0;
for (Integer num : list) {
sum = sum + num;
}
System.out.println("Sum = " + sum);
}
}
(You may get a different output.)
Task #1 added 1
Task #2 added 6
Task #3 added 8
Phase:0, Parties:4, Arrived:4
Task #3 added 9
Task #2 added 7
Task #1 added 8
Phase:1, Parties:4, Arrived:4
Sum = 39
Search WWH ::




Custom Search