Countdownlatch
Countdownlatch allows one or more threads to wait for another thread to complete the operation
When it is necessary to parse an Excel with multiple sheet data, multiple threads can be used, and each thread resolves the data in a sheet. The main thread waits for all threads to finish executing the sheet resolution operation.
Public classjoincountdownlatchtest () { Public Static voidMain (string[] args) {Thread parser1=NewThread (NewRunnable) _{ Public voidrun () {}}); Thread Parser2=NewThread (NewRunnable) _{ Public voidrun () {}}); Parser1.start (); Parser2.start (); Parser1.join (); Parser1.join (); System.out.print ("All parsers finished"); }}
The
Join is used to let the current thread of execution wait for the join thread to finish. The principle is to keep checking to see if the join thread is alive and let the current thread wait forever if the join thread survives. Until after the join () thread, the thread's This.notifyall () method is called, and the call to the Notifyall () method is implemented in the JVM.
public class countdownlatchtest{ static Countdownlatch C = new countdownlatch (2 public static void main (string[] args) throws interruptedexception{ new Thread (new Runnable () {System.out.println ( 1 2 "3"
The Countdownlatch constructor takes a parameter of type int as a counter, and if you want to wait for n points to complete, pass in N. When we call Countdownlatch's Countdown method, the await method of N minus 1,countdownlatch blocks the current thread until n becomes 0. Since the countdown method can be used in any of the fixed methods, that can make n threads. You just need to pass this countdownlatch reference to the thread. If a thread is processing slower, you can use the overloaded method await (long time, Timeunit unit).
The counter must be greater than 0, and the call to await () method does not block the current thread when the counter equals 0 o'clock. Countdownlatch It is not possible to reinitialize or modify the value of the internal counter of the Countdownlatch object. One thread calls the countdown method Happen-before another thread calls the await method.
Synchronization barrier Cyclicbarrier
Cyclicbarrier means a barrier (Barrier) that can be recycled (Cyclic). When a group of threads reaches a barrier, it is blocked until the last thread reaches the barrier, the barrier will open and all the threads intercepted by the barrier will continue to execute.
Cyclicbarrier the default constructor is cyclicbarrier (int parties), whose parameters represent the number of threads that the barrier intercepts, and each thread calls the await () method high speed Cyclicbarrier I have reached the barrier, and then the current Xian Chen is blocked.
Public classcyclicbarriretest{StaticCyclicbarrier C =NewCyclicbarrier (2); Public Static voidMain (string[] args) {NewThread (NewRunnable () { Public voidrun () {Try{c.await (); }Catch(Exception e) {} System.out.println (1); }}). Start (); Try{c.await (); }Catch(Exception e) {System.out.println (2); } }}
If new Cyclicbarrier (2) is modified to new Cyclicbarrire (3), the main thread and the child thread will wait forever because no third thread is executing the await method, that is, no third thread has reached the barrier, so the two threads that have previously reached the barrier will not continue to execute.
Cyclicbarrier is also provided to the constructor Cyclicbarrier (int parties, Runnable barrieraction) to execute barrieraction first when the thread arrives at the barrier.
Public classcyclicbarriertest2{StaticCyclicbarrier C =NewCyclicbarrier (2,NewA ()); Public Static voidMain (string[] args) {NewThread (NewRunnable () { Public voidrun () {Try{c.await (); }Catch(Exception e) {} System.out.println (1); }}). Start (); Try{c.await (); }Catch(Exception e) {} System.out.println (2); } Static classAImplementsrunnable{ Public voidrun () {System.out.println (3); } }}
The cyclicbarrier can be used to calculate the results of a multithreaded calculation of data at the end of the scene.
Public classBankwaterserviceImplementsrunnable{PrivateCyclicbarrier C =NewCyclicbarrier (4, This); PrivateExecutor Executor = Executors.newfixedthreadpool (4, This); Privateconcurrenthashmap<string, integer> sheetbankwatercount =NewConcurrenthashmap<string, integer>(); Private voidcount () { for(inti = 0; I < 4; i++) {Executor.execute (NewRunnable () { Public voidrun () {Sheetbankwatercount.put (Thread.CurrentThread (). GetName (),1); Try{c.await (); }Catch(Interruptedexception |brokenbarrierexception e) {E.printstacktrace (); } } }); } } Public voidrun () {intresult = 0; for(Entry<string, integer>Sheet:sheetBankWaterCount.entrySet ()) {Result+=Sheet.getvalue (); } sheetbankwatercount.put ("Result". Result); SYSTEM.OUT.PRINTLN (result); } Public Static voidMain (string[] args) {Bankwaterservice Bankwatercount=NewBankwaterservice (); Bankwatercount.count (); } }
Public classBankwaterserviceImplementsrunnable{PrivateCyclicbarrier C =NewCyclicbarrier (4, This); PrivateExecutor Executor = Executors.newfixedthreadpool (4, This); Privateconcurrenthashmap<string, integer> sheetbankwatercount =NewConcurrenthashmap<string, integer>(); Private voidcount () { for(inti = 0; I < 4; i++) {Executor.execute (NewRunnable () { Public voidrun () {Sheetbankwatercount.put (Thread.CurrentThread (). GetName (),1); Try{c.await (); }Catch(Interruptedexception |brokenbarrierexception e) {E.printstacktrace (); } } }); } } Public voidrun () {intresult = 0; for(Entry<string, integer>Sheet:sheetBankWaterCount.entrySet ()) {Result+=Sheet.getvalue (); } sheetbankwatercount.put ("Result". Result); SYSTEM.OUT.PRINTLN (result); } Public Static voidMain (string[] args) {Bankwaterservice Bankwatercount=NewBankwaterservice (); Bankwatercount.count (); } }
The difference between Cyclicbarrier and Countdownlatch
Countdownlatch counters can only be used once, while cyclicbarrier counters may be reset using the Reset () method. Cyclicbarrier also provides the Getnumberwaiting method to get the number of threads blocked by Cyclicbarrier. The Isbroker () method is used to understand whether the blocked thread is interrupted.
Semaphore
Semaphore is the number of threads used to control access to a particular resource at the same time, by coordinating individual threads to ensure reasonable use of public resources.
Semaphore can be used for traffic control, especially for applications with limited public resources, such as connecting databases.
Public classsemaphoretest () {Private Static Final intThread_count = 30; Private Static FinalExecutorservice ThreadPool =Executors.newfixedthreadpool (Thread_count); Private StaticSemaphore s =NewSemaphore (10); Public Static voidMain (string[] args) { for(inti = 0; i < Thread_count; i++) {Threadpool.executor (NewRunnable () {Try{s.acquire (); System.out.println ("Save Data"); S.release (); }Catch(Interruptedexception e) {}}); } threadpool.shutdown (); }}
Semaphore provides the following methods:
Acquire (): Get a license
Release (): Return license
int avaliablepermits (): Returns the currently available license certificate in the semaphore
int getqueuelength (): Returns the line that is waiting to get the license book
Boolean hasqueuedthreads (): Whether a thread is waiting to acquire a license
void reducepermits (int reduction): Reduces reduction licenses, protected
Collection getqueuedthreads (): Returns all thread collections waiting to get a license, protected
Exchanger
Exchanger is a tool class for inter-threading collaboration. The exchanger is used for data exchange between threads. It provides a synchronization point at which two threads can exchange data from each other. These two threads Exchange data through an Exchange method, and if the first thread executes the Exchange () method, it waits for the second thread to also execute the Exchange () method, and when two threads reach the synchronization point, the two threads can exchange data. Pass the data produced by this thread to the other party.
Exchange can be used in genetic algorithms where two people are chosen as mating objects, exchanging two data and using cross-rules to derive 2 mating results. At the same time exchanger can also be used for proofreading work. In order to avoid errors, the use of AB Gang two people to enter the data into Excel, the system loaded two Excel and two Excel data to proofread.
Public classexchangertest{Private Static FinalExchanger<string> exgr =NewExchanger<string>(); Private StaticExecutorservice ThreadPool = Executors.newfixedthreadpool (2); Public Static voidMain (string[] args) {Threadpool.execute (Newrunnble () { Public voidrun () {Try{String A= "Banker A"; Exgr.exchange (A); }Catch(interruptedexception) {}}}); Threadpool.execute (NewRunnable () { Public voidrun () {String B= "Banker B"; String A=Exgr.exchange (B); System.out.println ("A equals to B:" +a.equals (B)); } }); Threadpool.shutdown (); }}
If two threads have a non-executing exchange () method, they will wait. To avoid waiting all the time, you can call Exchange (V x, long timeout, timeunit unit) to set the maximum wait duration.
Concurrency tool classes in Java