JAVA5 Exchanger Data Interchange

Source: Internet
Author: User

For data exchange between two people, everyone wants to exchange data with each other after completing a certain transaction, the first person to come up with the data will wait until the second person is holding the data to exchange data with each other.

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 = "Zhang San"; 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 () + "return the data as '" + data2+ "'");} catch (Exception e) {}}}); Service.execute (new Runnable () {public void run () {try {String data1 = "John Doe"; 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 () + "swapped back data""+ data2 +" ' ");} catch (Exception e) {}}});}}

return Result:

Thread pool-1-thread-1 is taking the data ' Zhang San ' out of the thread pool-1-thread-2 is putting the data ' John Doe ' out of the thread pool-1-thread-1 swapped back the data for ' John Doe ' thread pool-1-thread-2 the data returned as ' Zhang San

  

JAVA5 Exchanger Data Interchange

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.