Java core knowledge point learning-multithreading countdown calculator CountDownLatch and data exchange Exchanger

Source: Internet
Author: User

This article will introduce all the new features in Java 5. One is the CountDownLatch, and the other is the Exchanger used for data exchange between threads. I. CountDownLatch1. what is CountDownLatch? CountDown counter: Call the CountDownLatch object's CountDown () method to reduce the counter by one. When the Count reaches 0, all or all the waiting persons start to execute. 2. how to use it? New CountDownLatch (1); Direct new, its constructor must pass an int type parameter, which means: count the number of times countDown must be invoked before threads can pass through await. Generally, there is a door with N bolts. To open the door, you must open all the bolts, corresponding to the thread, the thread is counted down before waiting. 3. for example, copy the code package com. amos. concurrent; import java. util. random; import java. util. concurrent. countDownLatch; import java. util. concurrent. executorService; import java. util. concurrent. executors ;/***@ ClassName: Count_Down_Latch_Test * @ Description: countdown * @ author: amosli * @ email: hi_amos@outlook.com * @ date Apr 27,201 4 11:51:43 */public class Count_Down_Latch_Test {public static void main (String [] args) {ExecutorService executorService = Executors. newCachedThreadPool (); final CountDownLatch countdownOrder = new CountDownLatch (1); // an order final CountDownLatch countdownAnwser = new CountD OwnLatch (3); // anwser for (int I = 0; I <3; I ++) {Runnable runnable = new Runnable () {public void run () {try {countdownOrder. await (); System. out. println ("Thread" + Thread. currentThread (). getName () + "preparing to accept command"); System. out. println ("Thread" + Thread. currentThread (). getName () + "Command accepted! "); Thread. sleep (new Random (). nextInt (1000); System. out. println ("Thread" + Thread. currentThread (). getName () + "response processing result! "); Countdownan.pdf. countDown ();} catch (Exception e) {e. printStackTrace () ;}}; executorService.exe cute (runnable); // start Thread pool} try {Thread. sleep (new Random (). nextInt (1000); System. out. println ("Thread" + Thread. currentThread (). getName () + "the command is coming soon !! "); CountdownOrder. countDown (); System. out. println (" Thread "+ Thread. currentThread (). getName () +" the command has been issued and is waiting for the result to be returned! "); Countdownanit. await (); System. out. println (" Thread "+ Thread. currentThread (). getName () +" all processing results have been received! ");} Catch (InterruptedException e) {e. printStackTrace () ;}} copy code 1 ). results are as follows: 2) The program description first creates a cache-able thread pool ---> then creates two CountDownLatch classes, one with a value of 1 and the other with a value of 3; -----> then, execute a for loop. in the loop, first implement a Runnable interface, and then add the Runnable interface to the thread pool. Where the Runnable interface, the first step is to wait for the counter to be 0. If it is 0, then the value of Counter 2 is reduced by one, and each cycle is reduced by one. When the third loop is executed, the thread is finished; -----> In the Runnable interface, when the counter is 0, the whole program cannot go down. In this case, the main method is to execute the CountDown method in the main thread, the counter minus one --------> Finally, wait until all threads are executed and return the final result. 4. extended -- the View Code in the official example is not the same as that in the previous example. Multiple, first set a wait, and then call the counter minus one to execute the final operation. countDownLatch is very suitable for running competitions. When the starting gun starts, all contestants start to run. II. exchanger1. what is Exchange? What is the role? It is used to exchange data between two people. After a transaction is completed, each person wants to exchange data with the other party. Only when the two people meet Will they exchange data. it's like an appointment between lovers. 2. how to use it? New Exchanger <V> (); the generic type is used here, that is, data in any format, basic type, object, and so on can be specified. it is important to note that the thread can exchange data only when it appears in pairs. the exchange method is exchange (x); Parameters: x the object to exchange parameter is the data to be exchanged to the other party. 3. example: copy the code package com. amos. concurrent; import java. util. random; import java. util. concurrent. exchanger; import java. util. concurrent. executorService; import java. util. concurrent. executors;/*** @ ClassName: ExchangerTest * @ Description: data exchange between threads Exchanger * @ author: amosli * @ email: hi_amos@outlook.com * @ date Apr 28,201 4 12:26:48 AM */public class ExchangerTest {public static void main (String [] args) {final Exchanger <String> exchanger = new Exchanger <String> (); ExecutorService newCachedThreadPool = Executors. newCachedThreadPool (); // thread 1 newCachedThreadPool.exe cute (new Runnable () {public void run () {try {String data1 = "111"; System. out. println ("Thread:" + Thread. currentThread (). getName () + "the data to be swapped out is:" + data1); Thread. sleep (new Random (). nextInt (1000); String exchange = exchanger. exchange (data1); System. out. println ("Thread:" + Thread. currentThread (). getName () + "the returned data is:" + exchange);} catch (InterruptedException e) {e. printStackTrace () ;}}); // thread 2 newCachedThreadPool.exe cute (new Runnable () {public void run () {try {String data1 = "hi_amos"; System. out. println ("Thread:" + Thread. currentThread (). getName () + "the data to be swapped out is:" + data1); Thread. sleep (new Random (). nextInt (1000); String exchange = exchanger. exchange (data1); System. out. println ("Thread:" + Thread. currentThread (). getName () + "the returned data is:" + exchange);} catch (InterruptedException e) {e. printStackTrace () ;}}) ;}} copy the code. Here, you only need to use the exchange () method.

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.