Java Concurrency: Counter &exechanger of thread synchronization mechanism

Source: Internet
Author: User
Tags connection pooling semaphore

First section Countdownlatch

(1) Initial knowledge of Countdownlatch

(2) Detailed Countdownlatch

The Countdownlatch is implemented by a counter, where the initial value of the counter is the number of threads. Each time a thread finishes its task, the value of the counter is reduced by 1, and when the counter value reaches 0 o'clock, it means that all the threads have completed the task, and then the thread waiting on the latch can resume execution of the task.

The main methods in Countdownlatch are as follows:

public Countdownlatch (int count), the Count (counter) in the constructor is actually the number of threads to wait for the lockout, this value can only be set once, and Countdownlatch does not provide any mechanism to reset the count value.

public void Countdown(), each time this method is called, the count value initialized in the constructor is reduced by 1, and the notification mechanism is done by this method.

public void await() throws Interruptedexception, the current thread that calls this method blocks until the value of the timer is 0.

(3) Countdownlatch Example

 Packagecom.test;ImportJava.util.concurrent.CountDownLatch; Public classcountdownlatchdemo{ Public Static voidMain (String args[])throwsexception{ countdownlatch latch = New countdownlatch (3); Worker Worker1=NewWorker ("Jack programmer 1", latch); Worker Worker2=NewWorker ("Rose Programmer 2", latch); Worker Worker3=NewWorker ("Json Programmer 3", latch);        Worker1.start ();        Worker2.start ();                Worker3.start ();        latch.await (); System.out.println ("Main Thread end!"); }        Static classWorkerextendsThread {PrivateString Workername; PrivateCountdownlatch latch;  PublicWorker (String workername,countdownlatch latch) { This. Workername =Workername;  This. Latch =latch; } @Override Public voidrun () {Try{System.out.println ("Worker:" +workername + "is begin."); Thread.Sleep (1000L); System.out.println ("Worker:" +workername + "is end."); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }//imitate to work; Latch.countdown (); }    }}            

The results of the above program operation are as follows:

worker:rose programmer 2 is begin. Worker:json programmer 3 is begin. Worker:jack programmer 1 is begin. Worker:jack Programmer 1 is end. Worker:json Programmer 3 is end. Worker:rose Programmer 2 is end. Main Thread End!

As can be seen from the results, the Mainthread executes to latch.await (), where it will be blocked until three threads are complete, Mainthread will continue to execute down

(4) References

This section simply describes how Countdownlatch is used, and so on, to understand its implementation mechanism, you can view the following articles

A, http://blog.itpub.net/30024515/viewspace-1432825/

B, HTTP://WWW.TUICOOL.COM/ARTICLES/MQNAFQ

Section II Cyclicbarrier

(1) Initial knowledge of Cyclicbarrier

(2) Cyclicbarrier example

Application Scenario: in a certain requirement, such as a large task, often need to allocate a lot of sub-tasks to execute, only when all the subtasks are completed to perform the main task, this time you can choose Cyclicbarrier.

Example:

 Packagecom.test;Importjava.util.concurrent.BrokenBarrierException;ImportJava.util.concurrent.CyclicBarrier; Public classcyclicbarrierdemo{ Public Static voidMain (String args[])throwsexception{ cyclicbarrier barrier = New cyclicbarrier (3,new  Totaltask ()); Billtask Worker1=NewBilltask ("111", barrier); Billtask Worker2=NewBilltask ("222", barrier); Billtask Worker3=NewBilltask ("333", barrier);        Worker1.start ();        Worker2.start ();        Worker3.start (); System.out.println ("Main Thread end!"); }         static class Totaltask extends  Thread {  Public voidrun () {System.out.println ("Once all the subtasks have been executed, the Executive director has started." "); }    }        Static classBilltaskextendsThread {PrivateString Billname; Privatecyclicbarrier Barrier;  Publicbilltask (String workername,cyclicbarrier barrier) { This. Billname =Workername;  This. Barrier =barrier; } @Override Public voidrun () {Try{System.out.println ("Downtown:" +billname + "operation begins:"); Thread.Sleep (1000L);//imitate the first operation;System.out.println ("Downtown:" +billname + "operation completed, waiting ..."); barrier.await (); //Assuming that one operation is not complete, the second depends on the result of the first operation. Will not continue until the node is reached.System.out.println ("All over, downtown" +billname + "just started back to work. "); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(brokenbarrierexception e) {e.printstacktrace (); }        }    }    }

The results of the above program operation are as follows:

Downtown: 111 Operation start: Downtown: 333 operation start: Main thread end! Downtown: 222 operation begins: Downtown: 333 completion, waiting ... Downtown: 222 operations completed, waiting ... Downtown: 111 operations completed, waiting ... once all the subtasks have been executed, the Executive Director has begun. //This is the end of the thread that finally arrived at the wait () method, and the city of 111 only started working behind it. It all ended, and the city's 222 began to work behind it. It all ended, and the city's 333 began to work behind it. 

Explanation: In this example, when constructing Cyclicbarrier, an instance object was passed into the inner class Totaltask (Totaltask inherits the thread, which is the implementation of the runnable), meaning: When all the threads are executing to the wait () method, They go back together to continue their work, but the last thread that arrives at the wait () method executes the Totaltask run () method, or if the implementation object of the runnable is not passed as a construction parameter when the construction Cyclicbarrier is constructed, When all threads are executed to the wait () method, they are returned directly to continue their work.

(3) The difference between Cyclicbarrier and Countdownlatch

The role of Countdownlatch is to allow 1 or n threads to wait for other threads to complete execution, while Cyclicbarrier allows n threads to wait for each other;
B, the Countdownlatch counter cannot be reset, while the Cyclicbarrier counter can be reset and used, so it is called a circular barrier.

Section III Semaphore

(1) Initial knowledge of semaphore

Semaphore in Java is used to transmit signals between threads, conceptually, the semaphore maintains a license set, semaphore only counts the available licenses, and takes action accordingly. Semaphores are often used in multithreaded code, such as database connection pooling.

(2) Semaphore example

Scenario: If a server resources are limited, at any one time only allow 3 people to access at the same time, there are altogether 10 people

 Packagecom.test;ImportJava.util.concurrent.Semaphore; Public classsemaphoredemo{ Public Static voidMain (String args[])throwsexception{ final Semaphore Semaphore = new Semaphore (3);//run only 3 people at a time for access                 for(inti=0;i<10;i++) {            Final intNo =i; Runnable Thread=NewRunnable () { Public voidrun () {Try{System.out.println ("User" +no+ "Connected:"); Thread.Sleep (300L); Semaphore.acquire (); //get permission to perform nextSystem.out.println ("User" +no+ "Start Access daemon ..."); Thread.Sleep (1000L);//impersonate the user to access the service process                        semaphore.release ();//release allows the next thread to access the backendSystem.out.println ("User +no+" access ends.) "); } Catch(interruptedexception e) {e.printstacktrace ();            }                }            }; Newthread (thread). Start (); } System.out.println ("Main Thread end!"); }}

The result of the above code operation is as follows:

User 1 Connected: User 3 connected: User 4 connected: User 2 connected: User 0 Connected: User 5 connected: User 7 connected: Main Thread end! User 6 Connected: User 8 connected: User 9 connected: User 3 start Access daemon ... User 4 start Access daemon ... User 2 start Access daemon ... End of user 4 visit. End of user 3 visit. User 7 start Access daemon ... User 0 start Access daemon ... User 8 start Access daemon ... End of user 2 visit. User 5 Start Access daemon ... End of user 0 visit. End of user 7 visit. User 1 start Access daemon ... End of user 8 visit. User 6 start Access daemon ... End of user 1 visit. User 9 start Access daemon ... End of user 5 visit. End of user 6 visit. End of user 9 visit. 

As can be seen from the results, 10 people come in at the same time, but only 3 people can access resources at the same time, release a permit to come in a

(3) References

Http://ifeve.com/semaphore/

Fourth Section Exchanger

(1) Initial knowledge of exchanger

Here the Exechanger and the previous description of the synchronization mechanism is not the same, the previous description of several synchronization mechanisms are implemented through counters, the following simple description of Exechanger, to see Exchanger application scenarios:

Note: As described above, we know that exchanger is used to exchange data between paired occurrences of a thread ( two threads have a single exchanger)

(2) Exechanger example

(3) References

Http://www.cnblogs.com/davidwang456/p/4179488.html

Java Concurrency: Counter &exechanger of thread synchronization mechanism

Related Article

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.