One, Condition
A scene, two threads, starting two threads at the same time, thread a number 1, 2, 3, then thread B number 4, 5, 6, last thread a number 7, 8, 9, program end, this involves the communication between threads.
Public classConditiontest {Static classNumberwrapper { Public intValue = 1; } Public Static voidMain (string[] args) {//to initialize a reentrant lock FinalLock lock =NewReentrantlock (); //first condition when the screen is output to 3 FinalCondition reachthreecondition =lock.newcondition (); //the second condition when the screen is output to 6 FinalCondition reachsixcondition =lock.newcondition (); //Numberwrapper is just to encapsulate a number, and you can share a digital object and set it to final//Note that this is not an integer, an integer is an immutable object FinalNumberwrapper num =NewNumberwrapper (); //Initialize a threadThread Threada =NewThread (NewRunnable () {@Override Public voidrun () {//need to get the lock firstLock.lock (); System.out.println ("Threada Get Lock"); Try{System.out.println ("Threada Start Write"); //a thread first outputs the first 3 digits while(Num.value <= 3) {System.out.println (num.value); Num.value++; } //output to 3 o'clock to signal, tell the B thread to start.reachthreecondition.signal (); } finally{lock.unlock (); System.out.println ("Threada release lock"); } lock.lock (); Try { //conditions to wait for output 6System.out.println ("Threada Get Lock"); Reachsixcondition.await (); System.out.println ("Threada Start Write"); //output remaining digits while(Num.value <= 9) {System.out.println (num.value); Num.value++; } } Catch(interruptedexception e) {e.printstacktrace (); } finally{lock.unlock (); System.out.println ("Threada release lock"); } } }); Thread threadb=NewThread (NewRunnable () {@Override Public voidrun () {Try{lock.lock (); System.out.println ("Threadb Get Lock"); Thread.Sleep (5000);//the await method releases the lock while(Num.value <= 3) { //wait for 3 output to complete the signalreachthreecondition.await (); } } Catch(interruptedexception e) {e.printstacktrace (); } finally{lock.unlock (); System.out.println ("Threadb release lock"); } Try{lock.lock (); System.out.println ("Threadb Get Lock"); //has received a signal to start outputting 4,5,6System.out.println ("threadb Start Write"); while(Num.value <= 6) {System.out.println (num.value); Num.value++; } //4,5,6 output finished, tell a thread 6 output is finishedreachsixcondition.signal (); } finally{lock.unlock (); System.out.println ("Threadb release lock"); } } }); //Start Two threadsThreadb.start (); Threada.start (); }}
Creation method: Created by Lock, Lock.newcondition ();
Common methods:
Await (): block until the same condition call the signal method.
Signal (): notification.
Summary: Condition must be used with lock (Wait (), notify () must be used with synchronized or the run will be an error java.lang.IllegalMonitorStateException ), more flexible than wait and notify, you can set up a variety of scenarios, such as reaching 3 in the previous example and reaching 62 conditions.
Two, Countdownlatch
Directly on the code:
Public classCountdownlatchtest { Public Static voidMain (string[] args) {FinalCountdownlatch C =NewCountdownlatch (3);//Total 3Thread T1 =NewThread (NewRunnable () {@Override Public voidrun () {Try{System.out.println ("Start Waiting"); C.await ();//blocking, waiting for Countdown, when countdown to 0 to do the back of the finishedSystem.out.println ("Finished"); } Catch(interruptedexception e) {e.printstacktrace (); } } }); Thread T2=NewThread (NewRunnable () {@Override Public voidrun () { for(inti=3;i>0;i--) {C.countdown ();//minus 1} } }); T1.start (); T2.start (); }
}
How to create: Create directly, new countdownlatch (int num);
Common methods:
Await (): Blocks until the countdown method has been executed num times.
Countdown (): Minus
Summary: Applies to a scenario where a thread waits for another thread.
Three, Cyclicbarrier
Think of the difference between the Countdownlatch and the code.
Public classmainmission {Privatecyclicbarrier Barrier; Private Final Static intThreadcounts = 5; Public voidrunmission () {Executorservice exec=Executors.newfixedthreadpool (threadcounts); //when new comes in, I find that this is similar to semaphore, where the thread grabs the position if the position is insufficient. Number if threadcounts+1 for the main thread to leave a seat, but the actual test found that as long as the equivalent of ThreadCount canBarrier=NewCyclicbarrier (threadcounts+1); for(inti=0;i<5;i++) {Exec.execute (NewMission (barrier)); } Try{barrier.await (); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(brokenbarrierexception e) {e.printstacktrace (); } Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("All tasks are done."); Exec.shutdown ();//Ifdoes not close, the program is always in a running state } Public Static voidMain (string[] args) {mainmission m=Newmainmission (); M.runmission (); }}classMissionImplementsrunnable{Privatecyclicbarrier Barrier; PublicMission (cyclicbarrier barrier) { This. Barrier =barrier; } @Override Public voidrun () {System.out.println (Thread.CurrentThread (). GetName ( )+ "Start performing Tasks"); Try { intSleepsecond =NewRandom (). Nextint (10) *1000; System.out.println (Thread.CurrentThread (). GetName ()+ "to perform" +sleepsecond+ "second task"); Thread.Sleep (Sleepsecond); } Catch(interruptedexception e) {e.printstacktrace (); } Try{barrier.await (); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(brokenbarrierexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Execution Complete"); }}
How to create: Create directly, new cyclicbarrier (int num);
Common methods:
Await (): blocks until the number of blocked threads reaches Num.
Summary: Think about the hundred meters run, all the players are in position before the start, the thread call to await means that I am ready.
Java Basics-java.util.concurrent The use of common classes under packages