Exchanger usage in java threads

Source: Internet
Author: User

Exchanger usage in java threads

Sometimes we need to pair the elements and synchronize the exchange threads, and use the exchange method to return the objects of our partners. In this case, we need to use the Exchanger class in the Thread class,

I use an instance to briefly describe how to use it and its role:

Import java. util. concurrent. exchanger; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class TestExchanger {/*** @ param args */public static void main (String [] args) {ExecutorService executor = Executors. newCachedThreadPool (); final Exchanger
 
  
Exchanger = new Exchanger
  
   
(); Executor.exe cute (new Runnable () {String data1 = "abc"; @ Overridepublic void run () {try {System. out. println (Thread. currentThread (). getName () + "Switching Data" + data1 + "); Thread. sleep (long) (Math. random () * 1000); String data2 = (String) exchanger. exchange (data1); System. out. println (Thread. currentThread (). getName () + "exchange data to" + data2);} catch (InterruptedException e) {e. printStackTrace () ;}}); executor.exe cute (new Runnable () {String data1 = "def"; @ Overridepublic void run () {try {System. out. println (Thread. currentThread (). getName () + "Switching Data" + data1 + "); Thread. sleep (long) (Math. random () * 1000); String data2 = (String) exchanger. exchange (data1); System. out. println (Thread. currentThread (). getName () + "exchange data to" + data2);} catch (InterruptedException e) {e. printStackTrace ();}}});}}
  
 

After the execution is completed, you will find that the data has been exchanged

Pool-1-thread-1 is exchanging data abc
Pool-1-thread-2 is switching data def
Pool-1-thread-2 swap data to abc
Pool-1-thread-1 swap data to def



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.