Cyclicbarrier
Cyclicbarrier is used for a level to block the residence thread, and when all threads are executed to the level, then the next operation is unified. Suppose a scene: Each thread represents a runner, and when the athletes are ready, they start together, and as long as one person is not ready, everyone waits.
code example:
Public classUsecyclicbarrier {Static classRunnerImplementsRunnable {Privatecyclicbarrier Barrier; PrivateString name; PublicRunner (cyclicbarrier barrier, String name) { This. Barrier =barrier; This. Name =name; } @Override Public voidrun () {Try{Thread.Sleep (1000 * (NewRandom ()). Nextint (5)); SYSTEM.OUT.PRINTLN (Name+ "Ready for OK."); Barrier.await (); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(brokenbarrierexception e) {e.printstacktrace (); } System.out.println (Name+ "go!!"); } } Public Static voidMain (string[] args)throwsIOException, interruptedexception {cyclicbarrier barrier=NewCyclicbarrier (3);//3Executorservice executor = Executors.newfixedthreadpool (3); Executor.submit (NewThread (NewRunner (barrier, "Zhangsan"))); Executor.submit (NewThread (NewRunner (barrier, "Lisi"))); Executor.submit (NewThread (NewRunner (barrier, "Wangwu"))); Executor.shutdown (); } } View Code
Result: The code after the await is not resumed until all the preparations are OK
Wangwu Prepare Ok.lisi prepare Ok.zhangsan prepare Ok.zhangsan go!! Lisi go!! Wangwu go!!
Countdownlacth
Countdownlatch is a counter lockout, the main function is to block the current thread through the await () method, and then wait for the counter to be reduced to 0, and then arouse these threads to continue execution. is often used to listen for certain initialization operations, and after the initialization is completed, the main thread is notified to continue working.
code example:
Public classUsecountdownlatch { Public Static voidMain (string[] args) {FinalCountdownlatch countdown =NewCountdownlatch (2); Thread T1=NewThread (NewRunnable () {@Override Public voidrun () {Try{System.out.println ("Go to Thread T1" + "Wait for other threads to finish ..."); Countdown.await (); System.out.println ("T1 thread continues to execute ..."); } Catch(interruptedexception e) {e.printstacktrace (); } } },"T1"); Thread T2=NewThread (NewRunnable () {@Override Public voidrun () {Try{System.out.println ("T2 Thread initialization operation ..."); Thread.Sleep (3000); System.out.println ("T2 thread initialization is complete, notify T1 thread to continue ..."); Countdown.countdown (); } Catch(interruptedexception e) {e.printstacktrace (); } } }); Thread T3=NewThread (NewRunnable () {@Override Public voidrun () {Try{System.out.println ("T3 thread initialization operation ..."); Thread.Sleep (4000); System.out.println ("T3 thread initialization is complete, notify T1 thread to continue ..."); Countdown.countdown (); } Catch(interruptedexception e) {e.printstacktrace (); } } }); T1.start (); T2.start (); T3.start (); }}View Code
Results:
T2 thread initialization operation ... t3 thread initialization operation ... Go to Thread T1 wait for other threads to finish ... t2 thread initialization is complete, notify T1 thread to continue ... t3 thread initialization is complete, notify T1 thread to continue ... t1 thread continues to execute ...
The difference between Cyclicbarrier and Countdownlatch
COUNTDOWNLACTH counters can only be used once, while cyclicbarrier counters may be reset using the Reset method. So cyclicbarrier can handle more complex business scenarios. For example, if you calculate an error, you can reset the counter and have the thread perform it again.
Cyclicbarrier also provides other useful methods, such as the Getnumberwaiting method, to get the number of threads Cyclicbarrier blocked. The IsBroken () method is used to understand whether the blocked thread is interrupted.
Semaphore
Semaphore and Countdownlatch are similar, the difference is that the value of semaphore can be released after the acquisition, not as Countdownlatch has been reduced to the end. It is also used more to limit the flow, similar to the function of the valve. If some resources are qualified to be accessed by up to n threads, then more than n hosts are not allowed to be accessed again, and when the existing thread ends, it is freed and then the new thread is allowed to come in. A bit like lock with unlock process. In contrast, he has two main methods:
- The Acquire (), which is used to obtain permissions, is similar to the Countdownlatch.countdown ();
- Release (), whose underlying implementation and acquire () is an inverse process for releasing permissions.
Current-Limit policy at the code level
Semaphore sema = new Semaphore (5);//5 In this case means a maximum of 5 threads are accepted.
Sema.aquire ();//Get authorization
code block;
Sema.release ();//Release
code example:
Public classUsesemaphore { Public Static voidMain (string[] args) {//thread PoolExecutorservice exec =Executors.newcachedthreadpool (); //can only be accessed by 5 threads at a time FinalSemaphore semp =NewSemaphore (5); //simulate 20 Client access for(intindex = 0; Index < 20; index++) { Final intNO =index; Runnable Run=NewRunnable () { Public voidrun () {Try { //obtaining a licenseSemp.acquire (); System.out.println ("Accessing:" +NO); //simulating the actual business logicThread.Sleep ((Long) (Math.random () * 10000)); //after the visit, releasesemp.release (); } Catch(Interruptedexception e) {}}; Exec.execute (run); } Try{Thread.Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } //System.out.println (Semp.getqueuelength ()); //exit thread poolExec.shutdown (); } }View CodeFuture
Its principle has been introduced before, the following look under the concurrent package of the future is how to use?
code example:
Public classUsefutureImplementsCallable<string>{ PrivateString para; Publicusefuture (String para) { This. para =para; } /*** Here is the real business logic, its execution may be slow*/@Override PublicString Call ()throwsException {//time-consuming simulation executionThread.Sleep (5000); String result= This. para + "Processing done"; returnresult; } //Main control function Public Static voidMain (string[] args)throwsException {String querystr= "Query"; //constructs a futuretask, and passes in a class that needs to really do business logic, and that class must be the class that implements the callable interfacefuturetask<string> future =NewFuturetask<string> (Newusefuture (QUERYSTR)); Futuretask<String> Future2 =NewFuturetask<string> (Newusefuture (QUERYSTR)); //creates a thread pool of fixed threads with a thread count of 1.Executorservice executor = Executors.newfixedthreadpool (2); //this commits the task to the future, then the call () method execution of the thread execution Realdata is turned on//the difference between the Submit and execute: The 1th is that submit can be passed to the instance object implementing the callable interface, and the 2nd is the return value of the Submit methodFuture F1= Executor.submit (future);//start a thread alone to execute theFuture F2 =Executor.submit (Future2); System.out.println ("Request Complete"); Try { //additional data operations can be done here, i.e. the main program executes other business logicSYSTEM.OUT.PRINTLN ("Handling the actual business logic ..."); Thread.Sleep (1000); } Catch(Exception e) {e.printstacktrace (); } //called to get the data method, if the call () method does not complete, it will still waitSYSTEM.OUT.PRINTLN ("Data:" +future.get ()); System.out.println ("Data:" +future2.get ()); Executor.shutdown (); }}View Code
Java.util.concurrent Common Class (Countdownlatch,semaphore,cyclicbarrier,future)