1. Countdownlatch of SynchronizerThe name of the class is translated in Chinese as: the countdown latch (the countdown latch). When manipulating threads, sometimes we want this thread to wait until a certain number of events have occurred. To handle this situation, the Concurrency API provides the Countdownlatch class, whichspecifies the number of events to wait at creation time, and a specified number of events must occur before the latch (latch) is released. Each time an event occurs, the counter decrements, and when the counter is reduced to 0 o'clock, the latch opens, the waiting thread wakes up, and then goes on. as you can know, the way to use it is simple: create a public reciprocal latch, await in a thread where it needs to wait (the maximum time to wait, use the method await (long wait,timeunit tu) wait to specify the length of the wait, TU Specifies the time unit for the duration, which is a value of an enumeration type, which is described in subsequent posts, until the latch is opened, and the other thread uses the same latch, just after a specified event is completed, the counter is decremented by calling Countdown. The instance code is as follows:
Import Java.util.concurrent.countdownlatch;public class Countdownletchtest {public static void main (string[] args) {// To create a latch, to turn on the latch must wait for the occurrence of 5 events Countdownlatch Countdownletch = new Countdownlatch (5);//thread one is the thread that uses the latch, new Threads (()->{ try {countdownletch.await ();} catch (Exception e) {e.printstacktrace ();} System.out.println ("Five events completed, so the output of this sentence oh:");}). Start (); New Thread (()->{system.out.println ("Completion of the first event"); Countdownletch.countdown ();}). Start (); New Thread (()->{system.out.println ("Completion of the second event"); Countdownletch.countdown ();}). Start (); New Thread (()->{system.out.println ("Completion of the third event"); Countdownletch.countdown ();}). Start (); New Thread (()->{system.out.println ("Fourth event execution complete"); Countdownletch.countdown ();}). Start (); New Thread (()->{system.out.println ("Fifth event execution complete"); Countdownletch.countdown ();}). Start ();} Output://The first event is completed//The second event is completed//The third event is completed///The fourth event is completed//fifth event executed//five events executed, so the output of this sentence oh. According to the output, if there is no waiting, the likelihood of such a result is very small, very small, very small.
2. Cyclicbarrier of SynchronizerThe name of the class is translated in Chinese as: Life cycle interception fence (periodic barrier). "Nice and comfortable" "In concurrent programming, multiple threads must wait at a predetermined point of execution until all the threads have reached their respective execution points, and then the barrier opens, and all the lines routine then execute, as long as one is not yet there and then waits until all is up." from the above, the use of the method is very simple: this class has two constructors: cyclicbarrier (int numthreads) cyclicbarrier (int numthreads,runnable action) The first parameter specifies the number of threads that need to reach the execution point, the second parameter specifies what to do after all the threads arrive, and then the thread that needs to synchronize uses the same cyclicbarrier, each thread that arrives at the execution point waits for await () (or a time is specified). When the specified number of threads arrives, the barrier opens and the operation executes if a specified operation is performed. instance code for subsequent actions without specifying a barrier open:
Import Java.util.concurrent.cyclicbarrier;public class Cyclicbarrierwithoutspecificafterwardaction {public static void Main (string[] args) {//does not specify the operation to be performed after all arrives at the waiting boundary point cyclicbarrier cyclicbarrier = new Cyclicbarrier (3); new Thread (()->{ System.out.println ("I ' m thread-0,i ' m on the await-point ..."); try {cyclicbarrier.await ();} catch (Exception e) {e.printstacktrace ();} System.out.println ("Ok,every thread is here, I ' m thread-0,i ' ll go ...");}). Start (); New Thread (()->{system.out.println ("I ' m thread-1,i ' m on the Await-point."); try {cyclicbarrier.await ();} catch (Exception e) {e.printstacktrace ();} System.out.println ("Ok,every thread is here, I ' m thread-1,i ' ll go ...");}). Start (); New Thread (()->{system.out.println ("I ' m thread-2,i ' m on the Await-point."); try {cyclicbarrier.await ();} catch (Exception e) {e.printstacktrace ();} System.out.println ("Ok,every thread is here, I ' m thread-2,i ' ll go ...");}). Start ();//output result://i ' m thread-0,i ' m on the await-point. I ' m thread-1,i ' m on the await-point. I ' m thRead-2,i ' m on the await-point. Ok,every thread is here, I ' M thread-2,i ' ll go...//ok,every thread was here, I ' M thread-0,i ' ll go...//ok,every thread is h Ere, I ' m thread-1,i ' ll go ...}}
Specifies the instance code for subsequent actions after the barrier is opened:
public class Cyclicbarrierwithspecificafterwardaction {public static void main (string[] args) {// Specifies the operation to be performed after all the waiting bounds are reached cyclicbarrier cyclicbarrier = new Cyclicbarrier (3, ()->{system.out.println ("Ok,every thread is Here,hope you every thread go dwon smoothly ... ");}); New Thread (()->{system.out.println ("I ' m thread-0,i ' m on the Await-point."); try {cyclicbarrier.await ();} catch (Exception e) {e.printstacktrace ();} System.out.println ("Ok,every thread is here, I ' m thread-0,i ' ll go ...");}). Start (); New Thread (()->{system.out.println ("I ' m thread-1,i ' m on the Await-point."); try {cyclicbarrier.await ();} catch (Exception e) {e.printstacktrace ();} System.out.println ("Ok,every thread is here, I ' m thread-1,i ' ll go ...");}). Start (); New Thread (()->{system.out.println ("I ' m thread-2,i ' m on the Await-point."); try {cyclicbarrier.await ();} catch (Exception e) {e.printstacktrace ();} System.out.println ("Ok,every thread is here, I ' m thread-2,i ' ll go ...");}). Start ();//output result://i ' m thread-0,i ' m on the Await-poInt.. I ' m thread-1,i ' m on the await-point. I ' m thread-2,i ' m on the await-point. Ok,every thread is here,hope you every thread go dwon smoothly...//ok,every thread are here, I ' m thread-2,i ' ll Go...//ok, Every thread is here, I ' M thread-0,i ' ll go...//ok,every thread was here, I ' M thread-1,i ' ll go ...}
3. Exchanger of Synchronizerthe Chinese translation of the Exchanger class is: exchanger. Perhaps the most interesting Synchronizer is exchanger, which is designed to simplify the exchange of data between two threads. The operation of the Exchanger object is simple: simply wait until two separate threads have called the exchanger method, and the data is exchanged at this time. The constructor is: exchanger<v>,v Specifies the type of data to be exchanged. The Interchange method is: v Exchanger (v Object) v Exchanger (v object,long wait,timeunit tu)The procedure used above is to create a common exchanger, and then two threads call the exchanger method at the execution point of each of the exchanged data, using the corresponding data type to receive the exchanged data. The instance code is as follows:
Import Java.util.concurrent.exchanger;public class Exchangetest {public static void main (string[] args) {exchanger< integer> exchanger = new exchanger<integer> (), New Thread (()->{int count = 1;while (count<5) {try {Integer Receive = Exchanger.exchange (count*2); System.out.println ("Got from Thread-1:" +receive); count++;} catch (Exception e) {e.printstacktrace ();}}}). Start (); New Thread (()->{int count = 1;while (count<5) {try {Integer receive = Exchanger.exchange (count*1); System.out.println ("Got form thread-0:" +receive); count++;} catch (Exception e) {e.printstacktrace ();}}}). Start ();} Run Result://got from thread-1:1//got form thread-0:2//got from thread-1:2//got form thread-0:4//got form thread-0:6//got From Thread-1:3//got from thread-1:4//got form thread-0:8}
4. Phaser of SynchronizerPhaser's Chinese translation is: Phase shifter (stage synchronizer). In short, Phaser is an enhanced version of Cyclicbarrier, Cyclicbarrier is waiting at an execution point, and when the specified number of threads arrive at the execution point, the threads go down, and Phaser is different, After this execution point, you can wait for the next execution point, which is a staged wait. The main scenario is to allow threads that represent one or more active stages to synchronize. constructor: Phaser ()/phaser (int numthreads): The parameter represents the number of threads that need to be synchronized, and if there is no relationship at the beginning, the number of threads that need to be synchronized during the run of the program can vary, in the way shown belowRegister to Synchronizer: int register () The return value is the stage of registration to this phase of the Synchronizer, although this is called the registration method, in fact, the stage Synchronizer does not know exactly which thread is registered, only know the number of threads that need to be synchronized at one stage increases aArrival: Int arrive ()/int arriveandawaitadvance ()/int arriveandderegister ()Three arrival methods, the return value is the current stage number. The first method is just to tell the calling thread that I'm here, but I don't wait for the other threads to finish, and then go down; the second one is me, and I'm going to wait until the specified number of threads arrives at the execution point, which is when the stage is complete, and I go down; the third way is, I'm here. And the coincidence is that I do not need to synchronize at this stage, so after I reached this stage of the execution point of deregistration, then the next stage needs to reach the specified point of execution of the number of threads minus one, where the logoff is only to tell the stage synchronizer the next phase of the number of threads to synchronize the amount of one minus a, In the end, which thread is less known. of course, the stage Synchronizer can also be prematurely invalidated, that is, the stage Synchronizer runs to a certain condition to lose the synchronization effect, this can be overridden by the Phaser class of the Boolean Onadvance () method, The two parameters that can be used to control whether the current stage Synchronizer is to be invalidated are the execution phase and the number of simultaneous threads that are currently registered. This method is called when the stage Synchronizer is pushed down, and if it returns true, it is immediately invalidated, if it returns false, then the next stage is pushed. The instance code used is as follows:
Import Java.util.concurrent.phaser;public class Phasertest {public static void main (string[] args) {//can also not override Onadvace () method, overriding is to return after a specific stage is executed, here is the execution to the third step return, if there is no rewrite, until all the registered threads run out of all stages can also end gracefully//to the constructor of 3 is a total of 3 threads registered to this Synchronizer, the problem comes, Sometimes not three threads have been working together to the end, you may walk to the left only one thread in action, when a thread arrives and does not need to be synchronized, to log off after the call, the method is: Phaser Phaser = new Phaser (3) {@ overrideprotected boolean onadvance (int phase,int parties) {if (phase==2| | Parties==0) return True;return false;}}; The new Thread (()->{//begins the first stage//Gets the current is in the second stage, and returns a negative number int i = phaser.getphase () if it has ended; System.out.println ("thread-0 phaser--" +i);p haser.arriveandawaitadvance ();//start second Stage I = Phaser.getphase (); System.out.println ("Thread-0 Phaser---" +i);p haser.arriveandawaitadvance ();//start Phase III i = Phaser.getphase (); System.out.println ("thread-0 Phaser----" +i);p haser.arriveandawaitadvance ();//start fourth Phase I = Phaser.getphase (); System.out.println ("Thread-0 Phaser-----" +i). Start (); New Thread (()->{//begins the first stage int i = Phaser.getphase (); System.out.println ("Thread-1 phaser--" +i);p haser.arriveandawaitadvance();//Start the second stage I = Phaser.getphase (); System.out.println ("Thread-1 Phaser---" +i);p haser.arriveandawaitadvance ();//start Phase III i = Phaser.getphase (); System.out.println ("Thread-1 Phaser----" +i);p haser.arriveandawaitadvance ();//start fourth Phase I = Phaser.getphase (); System.out.println ("Thread-1 Phaser-----" +i). Start (); New Thread (()->{//begins the first stage int i = Phaser.getphase (); System.out.println ("Thread-2 phaser--" +i);p haser.arriveandawaitadvance ();//start second Stage I = Phaser.getphase (); System.out.println ("Thread-2 Phaser---" +i);//write-off, in fact, the cancellation here is only to tell Phaser, the registered thread less one, specifically less which one it does not know// Phaser.arriveandderegister ();p haser.arriveandawaitadvance ();//Start the third stage I = Phaser.getphase (); System.out.println ("Thread-2 Phaser----" +i);p haser.arriveandawaitadvance ();//start fourth Phase I = Phaser.getphase (); System.out.println ("Thread-2 Phaser-----" +i). Start ();//Run result//thread-0 phaser--0//thread-1 phaser--0//thread-2 phaser--0//thread-2 Phaser---1//thread-1 Phaser---1//thread-0 Phaser---1//thread-1 phaser----2//thread-0 Phaser----2//thread-2 Phaser----2//threAd-1 Phaser------2147483645//thread-0 Phaser------2147483645//thread-2 Phaser------2147483645}}
Java Fundamentals-Concurrency utility (2)