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