Exchanger of the Java Synchronization tool class

Source: Internet
Author: User



Exchanger the synchronization point of a thread that can pair and swap elements in pairs. Each thread renders a method on the entry to the exchange method, matches the partner thread, and receives the object of its partner when it returns. Exchanger may be considered as SynchronousQueue a bidirectional form. Exchanger may be useful in applications such as genetic algorithms and pipeline design.

Simulation is used to achieve the exchange of data between the two, each person to complete a certain transaction after the exchange of data, the first person to take out the data will be waiting for the second person to come out of the data to each other to exchange data.

public class Exchangertest {public static void main (string[] args) {Executorservice service = Executors.newcachedthreadpo OL (); final Exchanger Exchanger = new Exchanger (); Service.execute (new Runnable () {public void run () {try {String data1 = "JL J "; SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "data" + Data1 + "swap out"); Thread.Sleep ((Long) (Math.random () *10000)); String data2 = (string) exchanger.exchange (data1); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "data returned as" + Data2);} catch (Exception e) {}}}); Service.execute (new Runnable () {public void run () {try {String data1 = "Ljy"; SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "data" + Data1 + "swap out"); Thread.Sleep ((Long) (Math.random () *10000)); String data2 = (string) exchanger.exchange (data1); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "data returned as" + Data2);} catch (Exception e) {}}});}}

Results:

Thread pool-1-thread-1 is swapping out the data jlj.
Thread pool-1-thread-2 is swapping out the data ljy.
The data returned by thread pool-1-thread-2 is JLJ
The data returned by thread pool-1-thread-1 is Ljy

Exchanger of the Java Synchronization tool class

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.