Use of Exchanger

Source: Internet
Author: User

Two threads can exchange synchronization points of objects. Every thread is enteringexchange Method, and accept the objects returned by other threads.

It is used to exchange data between two people. After a transaction is completed, each person wants to exchange data with the other party. The first person who obtains the data will wait until the second person receives the data, in order to exchange data with each other.
Constructor Summary
Exchanger()
Method Summary
V Exchange(V x)
Interrupted), And then transmits the given object to the thread and receives the object of the thread.
V Exchange(V x, long timeout, TimeUnit unit)
Interrupted, Or exceeds the specified wait time), and then transmits the given object to the thread, while receiving the object of the thread.
 
ExecutorService service = Exchanger exchanger = service.exe cute (Thread. sleep () (Math. random () * 10000 String data1 = "zxx" System. out. println ("Thread" + Thread. currentThread (). getName () + "changing data" + data1 + "String data2 = System. out. println ("Thread" + Thread. currentThread (). getName () + "the returned data is" +} service.exe cute (Thread. sleep () (Math. random () * 10000 String data1 = "lhm" System. out. println ("Thread" + Thread. currentThread (). getName () + "changing data" + data1 + "String data2 = System. out. println ("Thread" + Thread. currentThread (). getName () + "the returned data is" + }}

The running result is as follows:

Thread pool-1-thread -- 1-thread -- 1-thread -- 1-thread-2 The data returned is zxx

 

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.