Java. util. concurrent common classes (CountDownLatch, Semaphore, CyclicBarrier, Future ),

Source: Internet
Author: User

Java. util. concurrent common classes (CountDownLatch, Semaphore, CyclicBarrier, Future ),
CyclicBarrier

Javasicbarrier is used to block all threads at a level. When all threads are executed at the level, they will perform the next operation in a unified manner. Suppose a scenario: Each thread represents a runner. When the runners are ready, they start together. As long as one is not ready, everyone will wait.

Sample Code:

Public class UseCyclicBarrier {static class Runner implements Runnable {private CyclicBarrier barrier; private String name; public Runner (CyclicBarrier barrier, String name) {this. barrier = barrier; this. name = name ;}@ Override public void run () {try {Thread. sleep (1000 * (new Random ()). nextInt (5); System. out. println (name + "Prepare OK. "); barrier. await ();} catch (InterruptedException e) {e. prin TStackTrace ();} catch (BrokenBarrierException e) {e. printStackTrace ();} System. out. println (name + "Go !! ") ;}} Public static void main (String [] args) throws IOException, InterruptedException {javasicbarrier barrier = new javasicbarrier (3); // 3 ExecutorService executor = Executors. newFixedThreadPool (3); executor. submit (new Thread (new Runner (barrier, "zhangsan"); executor. submit (new Thread (new Runner (barrier, "lisi"); executor. submit (new Thread (new Runner (barrier, "wangwu"); executor. shutdown ();}}
View Code

Result: The code after await is executed only after the preparation is OK.

Wangwu preparation OK. lisi preparation OK. zhangsan preparation OK. zhangsan Go !! Lisi Go !! Wangwu Go !!
CountDownLacth

CountDownLatch is a counter lock. The main function is to block the current thread through the await () method, and then wait until the counter is reduced to 0, and then call these threads to continue execution. It is often used to listen for some initialization operations. After Initialization is completed, it notifies the main thread to continue working.

Sample Code:

Public class UseCountDownLatch {public static void main (String [] args) {final CountDownLatch countDown = new CountDownLatch (2); Thread t1 = new Thread (new Runnable () {@ Override public void run () {try {System. out. println ("Enter thread t1" + "wait for other threads to finish processing... "); countDown. await (); System. out. println ("t1 thread continues execution... ");} catch (InterruptedException e) {e. printStackTrace () ;}}, "t1"); Thread t2 = new Thread (new Runnable () {@ Override public void run () {try {System. out. println ("t2 thread initialization... "); Thread. sleep (1, 3000); System. out. println ("the t2 thread Initialization is complete, notifying t1 thread to continue... "); countDown. countDown ();} catch (InterruptedException e) {e. printStackTrace () ;}}); Thread t3 = new Thread (new Runnable () {@ Override public void run () {try {System. out. println ("t3 thread initialization... "); Thread. sleep (1, 4000); System. out. println ("t3 thread Initialization is complete, notifying t1 thread to continue... "); countDown. countDown ();} catch (InterruptedException e) {e. printStackTrace () ;}}); t1.start (); t2.start (); t3.start ();}}
View Code

Result:

Initialize the t2 thread... initialize the t3 thread... enter thread t1 and wait for other threads to finish processing... after the t2 thread Initialization is complete, notify the t1 thread to continue... the initialization of t3 thread is complete, notifying t1 thread to continue... t1 thread continues to execute...
CyclicBarrier and CountDownLatch

The CountDownLacth counter can only be used once, while the CyclicBarrier counter can be reset using the reset method. Therefore, javasicbarrier can handle more complex business scenarios. For example, if a calculation error occurs, You can reset the counter and re-execute the task.

CyclicBarrier also provides other useful methods. For example, the getNumberWaiting method can obtain the number of threads blocked by CyclicBarrier. The isBroken () method is used to check whether the blocked thread is interrupted.

Semaphore

Semaphore is similar to CountDownLatch. The difference is that the Semaphore value can be released after it is obtained, and it is not always reduced as CountDownLatch. It is also more used to limit the flow, similar to the function of the valve. If you limit that some resources can be accessed by a maximum of N threads, more than N masters are not allowed to be accessed by other threads. At the same time, when the existing thread ends, it will be released, then allow new threads to come in. It is similar to the lock and unlock processes. He also has two main methods:

Code-level throttling Policy

Semaphore sema = new Semaphore (5); // here, 5 indicates that a maximum of five threads are accepted.

Sema. aquire (); // get authorization

Code block;

Sema. release (); // release

Sample Code:

Public class UseSemaphore {public static void main (String [] args) {// thread pool ExecutorService exec = Executors. newCachedThreadPool (); // only five threads can simultaneously access final Semaphore semp = new Semaphore (5); // simulate 20 clients to access for (int index = 0; index <20; index ++) {final int NO = index; Runnable run = new Runnable () {public void run () {try {// obtain the license semp. acquire (); System. out. println ("Accessing:" + NO); // simulates the actual business logic Thread. sleep (long) (Math. random () * 10000); // release semp after access. release () ;}catch (InterruptedException e) {}}; exec.exe cute (run) ;}try {Thread. sleep (10);} catch (InterruptedException e) {e. printStackTrace ();} // System. out. println (semp. getQueueLength (); // exit the thread pool exec. shutdown ();}}
View CodeFuture

Its principles have been introduced before. Let's take a look at how the Future under the concurrent package is used?

Sample Code:

Public class UseFuture implements Callable <String> {private String para; public UseFuture (String para) {this. para = para;}/*** here is the real business logic, and its execution may be slow * // @ Override public String call () throws Exception {// Thread used to simulate execution. sleep (5000); String result = this. para + "processing completed"; return result;} // main Control Function public static void main (String [] args) throws Exception {String queryStr = "query "; // construct FutureTask and pass in the class that requires real business logic processing, this class must be the FutureTask class that implements the Callable interface <String> future = new FutureTask <String> (new UseFuture (queryStr )); futureTask <String> future2 = new FutureTask <String> (new UseFuture (queryStr); // create a thread pool with a fixed thread and the number of threads is 1. ExecutorService executor = Executors. newFixedThreadPool (2); // submit the job future here, the difference between the call () method execution of RealData is enabled by the thread and the submit method: the first point is that the submit can pass in the instance object that implements the Callable interface, and the second point is that the submit method has the returned value: Future f1 = executor. submit (future); // start a separate thread to execute Future f2 = executor. submit (future2); System. out. println ("request completed"); try {// here you can perform additional data operations, that is, the main program executes Other business logic System. out. println ("processing the actual business logic... "); Thread. sleep (1000);} catch (Exception e) {e. printStackTrace ();} // call the data retrieval method. If the call () method is not completed, it will still wait for System. out. println ("data:" + future. get (); System. out. println ("data:" + future2.get (); executor. shutdown ();}}
View Code

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.