Java Reference
In-Depth Information
// Terminate the phaser
phaser.forceTermination();
// Phaser is terminated
System.out.println("#3: isTerminated():" + phaser.isTerminated());
}
}
#1: isTerminated():false
Inside onAdvance(): phase = 0, Registered Parties = 0
Inside onAdvance(): phase = 1, Registered Parties = 0
#2: isTerminated():false
#3: isTerminated():true
Let's consider using a Phaser to solve a little complex task. This time, the Phaser works in multiple phases by
synchronizing multiple parties in each phase. Multiple tasks generate random integers in each phase and add them to
a List . After the Phaser is terminated, you compute the sum of all the randomly generated integers.
Listing 6-39 contains the code for a task. Let's call this task AdderTask . In its run() method, it creates a random
integer between 1 and 10, adds the integer to a List , and waits for a Phaser to advance. It keeps adding an integer to
the list in each phase of the Phaser until the Phaser is terminated.
Listing 6-39. An AdderTask Class Whose Instances Can Be Used with a Phaser to Generate Some Integers
// AdderTask.java
package com.jdojo.threads;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Phaser;
public class AdderTask extends Thread {
private Phaser phaser;
private String taskName;
private List<Integer> list;
private static Random rand = new Random();
public AdderTask(String taskName, Phaser phaser, List<Integer> list) {
this.taskName = taskName;
this.phaser = phaser;
this.list = list;
}
@Override
public void run() {
do {
// Generate a random integer between 1 and 10
int num = rand.nextInt(10) + 1;
System.out.println(taskName + " added " + num);
Search WWH ::




Custom Search