Data exchange between Java multithreading __java

Source: Internet
Author: User
Import Java.util.concurrent.Exchanger;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors; /** * Multithreading exchange of data use the exchanger method to pass the data that you want to pass, and accept the number of other threads passing when returning * @author Bowin */public class Exchangetest {public S  
        tatic void Main (string[] args) {Executorservice service =executors.newcachedthreadpool ();  
        Final exchanger<object> exchanger = new exchanger<> ();  
                    Service.execute (New Runnable () {@Override public void run () {try{  
                    String data1 = "Snack";  
                    SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "The data" +data1+ "to be replaced");  
                    Thread.Sleep ((Long) math.random () *10000); String data2 = (string) exchanger.exchange (data1);/wait for other threads to execute the Exchange method and get the results of other threads ' execution System.out.println (  
                           Thread +thread.currentthread (). GetName () + "The returned data is" +DATA2);  
                }catch (Exception e) {e.printstacktrace ();  
          
        }  
                  
            }  
        });  
                Service.execute (New Runnable () {@Override public void run () {  
                    try{String data1 = "Money";  
                    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 () + "Exchange back data is:" +DATA2);  
                }catch (Exception e) {e.printstacktrace ();  
    }  
                  
                  
            }  
        });   }  
}

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.