The phaser is a more resilient synchronization barrier. As with the sync barrier, a phaser allows a group of threads to
The barrier waits until the last thread arrives and the threads continue to execute. Phaser also offers and barrier
Action-equivalent operation.
Unlike synchronization barriers, which have a fixed number of threads, a phaser can coordinate an indefinite number of threads, which
Threads can be registered at any time.
Example code:
The following example creates 3 threads, prints a few letters, but does not execute immediately after the thread is created, but in the main program
Control it, 3 seconds after all processes start executing simultaneously
import java.util.concurrent.phaser;public class mytest {public static void Main (String[] args) {phaser phaser = new phaser (3) {// a total of 3 worker threads, So assign a value of 3@overrideprotected boolean onadvance (Int phase, int registeredparties) in the constructor {system.out.println ("\n========= Gorgeous split Line =============");return registeredparties == 0;}}; SYSTEM.OUT.PRINTLN ("program starts execution");char a = ' a ';for (int i = 0; i < 3; i++) { // Create and start 3 threads new mythread ((char) (a + i), phaser). Start ();} while (!phaser.isterminated ()) {// as long as Phaser does not end, the main thread loops to wait for Thread.yield ();} System.out.println ("End of Program");}} class mythread extends thread {private char c;private phaser phaser; Public mythread (Char c, phaser phaser) {this.c = c;this.phaser = Phaser;} @OVerridepublic void run () {while (!phaser.isterminated ()) {for (int i = 0; i < 10; i++) { // Print the current letter 10 times System.out.print (c + " ");} After printing the current letter, update it to the third letter after it, such as B update to E, for the next stage of printing c = (char) (c + 3);if (c > ' z ') {// if the letter Z is exceeded, a thread is dynamically reduced in phaser and exits the loop ends this thread phaser.arriveandderegister (); else {// instead, wait for other threads to reach the end of the stage, then go together to the next stage phaser.arriveandawaitadvance ();}}}
Java threading and concurrent programming practices----Synchronizer (Phaser)