Java 5 multithreading (7)-exchanger synchronization tool class

Source: Internet
Author: User
It is used to exchange data between two people. Each person wants to exchange data with the other party after completing a certain transaction, the first person who obtains the data will wait until the second person receives the data before they can exchange data. That is, when both threads reach the switching point, they can be switched. Public static void main (string [] ARGs ){

Executorservice service = executors. newcachedthreadpool (); Final exchanger = new exchanger (); service.exe cute (New runnable () {public void run () {try {string data1 = "money"; system. out. println ("Thread" + thread. currentthread (). getname () + "changing data" + data1 + "); thread. sleep (long) (math. random () * 10000 )); string data2 = (string) exchanger. Exchange (data1); System. out. println ("Thread" + thread. currentthread (). getname () + "the returned data is" + data2);} catch (exception e) {}}); service.exe cute (New runnable () {public void run () {try {string data1 = "drugs"; system. out. println ("Thread" + thread. currentthread (). getname () + "changing data" + data1 + "); thread. sleep (long) (math. random () * 10000 )); String data2 = (string) exchanger. Exchange (data1 ); System. out. println ("Thread" + thread. currentthread (). getname () + "the returned data is" + data2);} catch (exception e ){}}});

}

The running result is as follows:

Reprinted please indicate the source: http://blog.csdn.net/johnny901114/article/details/8696019

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.