Java Thread Synchronization helper class exchanger-interchange

Source: Internet
Author: User

The synchronization point of the 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.

ImportJava.util.Random;ImportJava.util.concurrent.Exchanger;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classExchangertest { Public Static voidMain (string[] args) {Executorservice service=Executors.newcachedthreadpool (); FinalExchanger<string> Exchanger =NewExchanger<string>(); Service.execute (NewRunnable () {@Override Public voidrun () {Try{String data1= "Duwenlei"; System.out.println ("Thread" +thread.currentthread (). GetName () + "data to be swapped for" +data1); System.out.println ("Thread" +thread.currentthread (). GetName () + "waiting for each other"); Thread.Sleep (NewRandom (). Nextint (10000)); String data2= Exchanger.exchange (data1);//Start exchanging dataSYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "data after Interchange is" +data2); } Catch(interruptedexception e) {e.printstacktrace ();        }            }        }); Service.execute (NewRunnable () {@Override Public voidrun () {Try{String data1= "Shenjing"; System.out.println ("Thread" +thread.currentthread (). GetName () + "data to be swapped for" +data1); System.out.println ("Thread" +thread.currentthread (). GetName () + "waiting for each other"); Thread.Sleep (NewRandom (). Nextint (10000)); String data2=Exchanger.exchange (DATA1); System.out.println ("Thread" +thread.currentthread (). GetName () + "data after Interchange is" +data2); } Catch(interruptedexception e) {e.printstacktrace ();        }            }        });    Service.shutdown (); }}

Java Thread Synchronization helper class exchanger-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.