Java concurrency: Counter of thread synchronization mechanism & amp; Exechanger, java counter

Source: Internet
Author: User

Java concurrency: counters of thread synchronization mechanism & Exechanger, java counters

Section 1 CountDownLatch

(1) first recognized CountDownLatch

 

(2) Detail CountDownLatch

CountDownLatch is implemented by a counter. The initial value of the counter is the number of threads. Every time a thread completes its own task, the counter value is reduced by 1. When the counter value reaches 0, it indicates that all threads have completed the task, then the thread waiting on the lock can resume the execution task.

The main method of CountDownLatch is as follows:

Public CountDownLatch (int count), the count (Counter) in the constructor is actually the number of threads to wait for locking. This value can only be set once, countDownLatch does not provide any mechanism to reset the Count value.

Public voidCountDown(), Every time this method is called, the initial count value in the constructor is reduced by 1, and the notification mechanism is implemented by this method.

Public voidAwait() Throws InterruptedException. The current thread that calls this method will be blocked until the timer value is 0.

 

(3) CountDownLatch example

Package com. test; import java. util. concurrent. countDownLatch; public class CountDownLatchDemo {public static void main (String args []) throws Exception {CountDownLatch latch = new CountDownLatch (3); Worker worker1 = new Worker ("Jack Programmer 1 ", latch); Worker worker2 = new Worker ("Rose programmer 2", latch); Worker worker3 = new Worker ("Json Programmer 3", latch); worker1.start (); worker2.start (); worker3.start (); latch. awai T (); System. out. println ("Main thread end! ");} Static class Worker extends Thread {private String workerName; private CountDownLatch latch; public Worker (String workerName, CountDownLatch latch) {this. workerName = workerName; this. latch = latch ;}@ Override public void run () {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 block e. printStackTrace ();} // work in imitation; latch. countDown ();}}}

The program running result is 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 will be blocked in latch. await (); until all three threads are completed, the MainThread will continue to execute

 

(4) References

This section briefly describes how to use CountDownLatch. For more information, see the following articles.

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

B. http://www.tuicool.com/articles/mQnAfq

 

Section 2 CyclicBarrier

(1) CyclicBarrier

 

(2) CyclicBarrier example

Application scenarios:In a certain requirement, for example, a large task, many subtasks are often assigned for execution. The chief service can be executed only when all subtasks are completed, in this case, you can choose CyclicBarrier.

Example:

Package com. test; import java. util. concurrent. brokenBarrierException; import java. util. concurrent. cyclicBarrier; public class javasicbarrierdemo {public static void main (String args []) throws Exception {javasicbarrier barrier = new javasicbarrier (3, new TotalTask ()); billTask worker1 = new BillTask ("111", barrier); BillTask worker2 = new BillTask ("222", barrier); BillTask worker3 = new BillTask ("333", barrie R); worker1.start (); worker2.start (); worker3.start (); System. out. println ("Main thread end! ");} Static class TotalTask extends Thread {public void run () {System. out. println. ") ;}} Static class BillTask extends Thread {private String billName; private javasicbarrier barrier; public BillTask (String workerName, javasicbarrier barrier) {this. billName = workerName; this. barrier = barrier;} @ Override public void run () {try {System. out. println ("City:" + billName + "operation start:"); Thread. sleep (1000L); // simulates the first operation; System. out. println ("City:" + billName + "Operation completed, waiting... "); barrier. await (); // assume once The second is dependent on the result of the first operation. System. out. println ("all ends, city" + billName + "to start the subsequent work. ");} Catch (InterruptedException e) {e. printStackTrace ();} catch (BrokenBarrierException e) {e. printStackTrace ();}}}}

The program running result is as follows:

City: 111 operation start: City: 333 operation start: Main thread end! City: 222 operation started: City: 333 operation completed, waiting... city: 222 operation completed, waiting... city: 111 operation completed, waiting... after all the sub-tasks are completed, the Executive Director is started. // This sentence indicates that all the threads that finally arrive at the wait () method are executed, and the subsequent work is started in the urban district 111. All of them are finished, and only 222 of the city is started. All of them are finished, and only 333 of the city is started.

Note: In this example, when constructing javasicbarrier, the Instance Object of the internal class TotalTask (TotalTask inherits Thread and is the implementation of Runnable) is passed in. Its meaning is: when all threads execute the wait () method, they return to continue their work together, but the last thread that reaches the wait () method will execute the run () of TotalTask () if the Runnable implementation object is not passed into the constructor when constructing javasicbarrier, all threads will directly return their work together when they execute the wait () method.

 

(3) differences between CyclicBarrier and CountDownLatch

A. CountDownLatch is used 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 counter of CountDownLatch cannot be reset, while the counter of CyclicBarrier can be reset and used. Therefore, it is called a circular barrier.

 

 

Section 3 Semaphore

(1) Semaphore

In Java, Semaphore is used to transmit signals between threads. In terms of concept, semaphores maintain a license set. Semaphore only counts available licenses and takes corresponding actions. Semaphores are often used in multi-threaded code, such as database connection pools.

 

(2) Semaphore example

Scenario: Assume that a server has limited resources. At any time, only three people are allowed to access the server at the same time. At this time, a total of 10 people are allowed.

Package com. test; import java. util. concurrent. semaphore; public class SemaphoreDemo {public static void main (String args []) throws Exception {final Semaphore semaphore = new Semaphore (3 ); // only three people are running at a time for access (int I = 0; I <10; I ++) {final int no = I; Runnable thread = new Runnable () {public void run () {try {System. out. println ("user" + no + "connected:"); Thread. sleep (300L); semaphore. acquire (); // obtain the permission System for subsequent execution. o Ut. println ("user" + no + "start to access the background program... "); Thread. sleep (1000L); // imitates semaphore during user access to the service. release (); // release allows the next thread to access the background System. out. println ("user" + no + "access ends. ");} Catch (InterruptedException e) {e. printStackTrace () ;}}; new Thread (thread ). start ();} System. out. println ("Main thread end! ");}}

The above code runs as follows:

User 1 connected: User 3 connected: User 4 connected: User 2 connected: user 0 connected: User 5 connected: user 7 is connected: Main thread end! User 6 connected: User 8 connected: User 9 connected: User 3 started to access the background program... user 4 starts to access the background program... user 2 starts to access the background program... user 4 access is complete. User 3's access is complete. User 7 started to access the background program... user 0 started to access the background program... user 8 started to access the background program... user 2 ended to access. User 5 starts accessing the background program... user 0 ends. User 7 Access is complete. User 1 starts accessing the background program... user 8 ends. User 6 starts accessing the background program... user 1 ends. User 9 starts accessing the background program... user 5 ends. User 6 access is complete. User 9 access is complete.

It can be seen from the results that 10 people come in at the same time, but only 3 people can access resources at the same time, releasing one to allow one

 

(3) References

Http://ifeve.com/semaphore/

 

Section 4 Exchanger

(1) first recognized Exchanger

The Exechanger here is different from the synchronization mechanisms described above. The synchronization mechanisms described above are all implemented through counters. The following describes the Exechanger and the application scenarios of Exchanger:

Note: As described above, we know that Exchanger is used between the threads that appear in pairs (Two threads have one Exchanger.) Exchange data

 

(2) Exechanger example

 

(3) References

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

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.