The use of the Java advanced---->thread Phaser

Source: Internet
Author: User

Phaser provides a dynamic parties count, which is more convenient than Cyclicbarrier class operation parties. It's a new class for jdk1.7, so let's learn how to use it today.

Phaser simple use of a, phaser Arriveandawaitadvance method
 PackageCom.linux.thread.thread;ImportJava.util.concurrent.Phaser; Public classPhaserRun1 { Public Static voidMain (string[] args) {Phaser Phaser=NewPhaser (3);  for(inti = 0; I < 3; i++) {Threada Threada=NewThreada (Phaser);        Threada.start (); }    }    Static classThreadaextendsThread {PrivatePhaser Phaser;  PublicThreada (Phaser Phaser) { This. Phaser =Phaser; } @Override Public voidrun () {System.out.println (Thread.CurrentThread (). GetName ( )+ "A Begin" +System.currenttimemillis ());            Phaser.arriveandawaitadvance (); System.out.println (Thread.CurrentThread (). GetName ()+ "A End" +System.currenttimemillis ()); }    }}

The results of one run are as follows:

thread-01501381934550thread-11501381934550thread-2  1501381934550thread-11501381934550thread-2 1501381934550 Thread-01501381934560

The code for modifying the main method above is as follows:

 Public Static void throws interruptedexception{    new Phaser (3);    Phaser.register ();      for (int i = 0; i < 3; i++) {        new  Threada (phaser);        Threada.start ();    }    Thread.Sleep (the);    Phaser.arriveandderegister ();}

The effect of the operation is as follows:

There are several ways to control the effect of running synchronously between multiple threads, the effect of canceling synchronization on one thread, the ability to wait at a specified barrier, support for interrupts or non-disruptive functions while waiting, and the use of Java concurrency classes to group synchronization controls on threads. Phaser is more powerful than the Cyclicbarrier class and is recommended for use.

Friendship Link

The use of the Java advanced---->thread Phaser

Related Article

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.