Java concurrent Programming-phase shifter

Source: Internet
Author: User

There are 2 important states in the phase shifter (Phaser), namely phase and party.
Phase is the stage, the initial value of 0, when all the threads to complete the task, while starting the next round of tasks, meaning that the current phase has ended, into the next stage, the value of phase automatically added 1.
A party is a thread, and party=4 means that the Phaser object currently manages 4 threads.
Phaser also has an important method that often needs to be overloaded, which is the boolean onadvance (int phase, int registeredparties) method. This method has 2 functions:
1. This method is automatically called when each stage is executed, so the code that overloads this method writes is executed at the end of each stage, equivalent to Cyclicbarrier's barrieraction.
2. When this method returns true, it means that phaser is terminated, so you can set the return value of this method smartly to terminate all threads.
For example, if this method returns a value of phase>=3, it means that the program terminates when the entire thread executes 4 stages.
Phaser divides the tasks performed by multiple threads into multiple phases (phase), programming to clarify the tasks of each stage, each phase can have any participant, the thread can be registered at any time and participate in a phase, when all the threads in a phase are completed successfully, Phaser's Onadvance () is called and can be overridden to add custom processing logic (similar to the runnable interface used by the loop barrier), and then the Phaser class automatically goes to the next stage. This loops until the phaser no longer contains any participants.
Register (), Bulkregister (), dynamically add one or more participants.
Arrive (), called when a participant finishes a task
Arriveandderegister (), Task complete, cancel your own registration.
Arriveandawaitadvance (), completing its own wait for other participants to complete: into the block until Phaser successfully enters the next stage.
Awaitadvance (), awaitadvanceinterruptibly (), waits for the phaser to enter the next stage, the parameter is the number of the current stage, which can set the timeout and process the interrupt request.
In addition, an important feature of Phaser is that multiple phaser can form a tree structure, Phaser provides a construction method to specify the parent object of the current object, and when a child object participant >0, it is automatically registered to the parent object; when = 0, automatically de-registers.

[Java]package Org.suxuan;import Java.util.concurrent.phaser;import        Java.util.concurrent.atomic.atomicreferencearray;public class Phaserdemo {public static void main (string[] args) {        final int workers = 2;        Final int worklength = 10;        Final Phaser Phaser = new Phaser (workers + 1);        Final atomicreferencearray<string> lane1 = new atomicreferencearray<string> (new String[worklength]);        Final atomicreferencearray<string> lane2 = new atomicreferencearray<string> (new String[worklength]); New Thread ("Producer 1") {@Override public void run () {for (int i = 0; i < Workl Ength;                    i++) {$sleep (20);                    Lane1.set (i, "lane1-answer-" + i); System.out.printf ("[%-17s] working in Lane1 finished phase [%d]%n", Thread.CurrentThread (). Getn                    Ame (), phaser.getphase ());          Phaser.arriveandawaitadvance ();      }}}.start (); New Thread ("slower producer 2") {@Override public void run () {for (int i = 0; I &lt ; Worklength;                    i++) {$sleep (40);                    Lane2.set (i, "lane2-answer-" + i); System.out.printf ("[%-17s] working in Lane2 finished phase [%d]%n", Thread.CurrentThread (). Getn                    Ame (), phaser.getphase ());                Phaser.arriveandawaitadvance ();        }}}.start ();  New Thread ("Slow consumer") {@Override public void run () {for (int start = 0; start < Worklength; {System.out.printf ("[%-17s] about-to-wait for phase [%d] completion%n", T                    Hread.currentthread (). GetName (), start);                    int phaseinprogress = phaser.awaitadvance (start);   Read all the recent completed phases.                 for (int i = start; i < phaseinprogress; i++) {System.out.printf ("[%-17s] Read [%s] & [%s] from phase [%d]%n], Thread.CurrentThread (). GetName (), Lane1.get (i), Lane2.                    Get (i), i);                    } start = phaseinprogress;                $sleep (80);        }}}.start ();    Phaser.arriveandderegister ();        } private static void $sleep (long Millis) {try {thread.sleep (Millis); } catch (Interruptedexception e) {}}}[/java]

The


Phaser is initialized to 3, and after the customer thread cancels its own registration (only two producer threads are synchronized), the awaitadvance does not block and it returns directly.
Two producer threads, which in turn generate results to be placed in Atomicreferencearray. After each sleep 80Ms, the consumer thread prints out the results from the result set that are currently completed.
The result of a run is as follows:

[Java] [Slow consumer] about-to-wait for phase [0] Completion[producer 1] working in Lane1 finished phase [0][slower p Roducer 2] Working in Lane2 finished phase [0][slow consumer] read [lane1-answer-0] & [lane2-answer-0] from phase [0]       [Producer 1] working in Lane1 finished phase [1][slower Producer 2] working in Lane2 finished phase [1][producer 1 ] Working in Lane1 finished phase [2][slow consumer] about-to-wait for phase [1] completion[slow consumer] r  EAD [lane1-answer-1] & [lane2-answer-1] from phase [1][slower Producer 2] working in Lane2 finished phase [2][producer 1] Working in Lane1 finished phase [3][slower Producer 2] working in Lane2 finished phase [3][producer 1] W Orking in Lane1 finished phase [4][slower Producer 2] working in Lane2 finished phase [4][producer 1] working in LA Ne1 finished phase [5][slow consumer] about-to-wait for phase [2] completion[slow consumer] read [lane1-answer-2] & [Lane2-anSwer-2] from phase [2][slow consumer] read [lane1-answer-3] & [lane2-answer-3] from phase [3][slow consumer] r  EAD [lane1-answer-4] & [lane2-answer-4] from phase [4][slower Producer 2] working in Lane2 finished phase [5][producer 1] Working in Lane1 finished phase [6][slower Producer 2] working in Lane2 finished phase [6][slow consumer] A Bout to wait for phase [5] completion[slow consumer] read [lane1-answer-5] & [lane2-answer-5] from phase [5][slow Consumer] read [lane1-answer-6] & [lane2-answer-6] from phase [6][slower Producer 2] working in Lane2 finished PHA SE [7][producer 1] working in Lane1 finished phase [7][producer 1] working in Lane1 finished phase [8][slowe    R Producer 2] working in Lane2 finished phase [8][producer 1] working in Lane1 finished phase [9][slow consumer About-to-wait for phase [7] Completion[slow consumer] read [lane1-answer-7] & [lane2-answer-7] from phase [7][SL OW consumer] read [lANE1-ANSWER-8] & [lane2-answer-8] from phase [8][slower Producer 2] working in Lane2 finished phase [9][slow consumer About-to-wait for phase [9] completion[slow consumer] read [lane1-answer-9] & [lane2-answer-9] from phase [9] [/java]

Java concurrent Programming-phase shifter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.