Java Concurrency Tool class inter-threading data exchange tool exchanger

Source: Internet
Author: User

Exchanger is a tool class for inter-thread co-use, primarily for data exchange between threads. It provides a synchronization point at which two threads can exchange data with each other. Two threads Exchange data through Exchange methods, and if one thread executes an Exchange method, it waits for another thread to execute the Exchange method, and when two threads reach the synchronization point, the two threads can exchange data. Transfer the data generated by this thread to the other party.

Exchanger can be used for the work of mutual proofreading, for example, we want to put the transaction data generated by manual input into the system, in order to avoid errors, we use AB two simultaneous input method, when the input is completed, the system load AB two input data, check whether the error.

The simulation examples are as follows:

  

 Public classExchangertest {//Defining the Exchanger    Private Static FinalExchanger<string> Exchanger =NewExchanger<string>(); Private StaticExecutorservice ThreadPool = Executors.newfixedthreadpool (2);  Public Static voidMain (string[] args) {Threadpool.execute (NewRunnable () {@Override Public voidrun () {String stra= "A record Data"; Try{exchanger.exchange (stra); } Catch(interruptedexception e) {e.printstacktrace ();        }            }        }); Threadpool.execute (NewRunnable () {@Override Public voidrun () {Try{String StrB= "B Record Data"; String Stra=Exchanger.exchange (StrB);                    System.out.println (Stra.equals (StrB));                Exchanger.exchange (StrB); } Catch(interruptedexception e) {e.printstacktrace ();    }            }        }); }}

If two threads have one without the Exchange () method, you can wait until you are concerned about special circumstances and avoid waiting for the maximum wait time to be set using Exchange (V x,longtimeout,timeunit unit).

Java Concurrency Tool class inter-threading data exchange tool exchanger

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.