Created
August 16, 2012 16:41
-
-
Save ellios/3371555 to your computer and use it in GitHub Desktop.
Phaser Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package me.ellios.concurrency; | |
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.concurrent.Phaser; | |
/** | |
* Author: ellios | |
* Date: 12-8-14 Time: 下午5:03 | |
*/ | |
public class PhaserDemo { | |
public static void main(String args[]) throws Exception { | |
// | |
final int count = 10; | |
final int phaseToTerminate = 10; | |
final Phaser phaser = new Phaser(count) { | |
@Override | |
protected boolean onAdvance(int phase, int registeredParties) { | |
System.out.println(); | |
System.out.println("******************" + phase + "***********************"); | |
return phase == phaseToTerminate || registeredParties == 0; | |
} | |
}; | |
for(int i = 0; i < count; i++) { | |
final Thread thread = new Thread(new Task(i, phaser)); | |
thread.start(); | |
} | |
awaitPhase(phaser, phaseToTerminate); | |
System.out.println("*******************done***********************"); | |
} | |
public static class Task implements Runnable { | |
// | |
private final int id; | |
private final Phaser phaser; | |
public Task(int id, Phaser phaser) { | |
this.id = id; | |
this.phaser = phaser; | |
} | |
@Override | |
public void run() { | |
while(!phaser.isTerminated()) { | |
System.out.print(id + ","); | |
phaser.arriveAndAwaitAdvance(); | |
} | |
} | |
} | |
public static void awaitPhase(Phaser phaser, int phase) { | |
int p = phaser.register(); // assumes caller not already registered | |
while (p <= phase) { | |
if (phaser.isTerminated()) { | |
break; // ... deal with unexpected termination | |
} else { | |
p = phaser.arriveAndAwaitAdvance(); | |
} | |
} | |
phaser.arriveAndDeregister(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment