Java multithreaded programming using Exchanger data Interchange Instance _java

Source: Internet
Author: User

To achieve the exchange of data between two people, each person in the completion of a certain transaction to exchange data with each other, the first person to take out the data will be waiting for the second person to hold the data to each other to exchange data.

Copy Code code as follows:

Package com.ljq.test.thread;

Import Java.util.concurrent.Exchanger;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

public class Exchangertest {

public static void Main (string[] args) {

Executorservice service = Executors.newcachedthreadpool ();
Final EXCHANGER EXCHANGER = new exchanger ();
Service.execute (New Runnable () {
public void Run () {
try {

String data1 = "John";
SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "is putting data ' + data1 + ' ' in exchange for");
Thread.Sleep ((Long) (Math.random () *10000));
String data2 = (string) exchanger.exchange (data1);
SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "return the data as '" + data2+ "");
}catch (Exception e) {

}
}
});
Service.execute (New Runnable () {
public void Run () {
try {
String data1 = "Dick";
SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "is putting data ' + data1 + ' ' in exchange for");
Thread.Sleep ((Long) (Math.random () *10000));
String data2 = (string) exchanger.exchange (data1);
SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "return the data as '" + Data2 + "");
}catch (Exception e) {

}
}
});
}
}

return Result:

Copy Code code as follows:

Thread pool-1-thread-1 is changing the data ' John ' out
Thread pool-1-thread-2 is changing the data ' dick ' out
The data returned by the thread pool-1-thread-1 is ' dick '
The data returned by the thread pool-1-thread-2 is ' John '

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.