Tool classes for threads (Exchange)

Source: Internet
Author: User

public class Exchanger<v>extends Object

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.

Instance:

Import Java.util.concurrent.Exchanger;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

/**
* Exchange of data between threads
*
* @author Wangyi
* @version 1.0 <br/>
* <a href= "www.baidu.com" > Baidu </a>
*/
public class Exchagertest {
public static void Main (string[] args) {
Executorservice service = Executors.newcachedthreadpool ();
Exchanger<string> Exchange = new exchanger<string> ();
Service.execute (New mythread<string> ("Love", Exchange, "Love"));
Service.execute (New mythread<string> ("Guan Xiaotong", Exchange, "Guan Xiaotong"));
Service.shutdown ();

}

Static Class Mythread<t> extends Thread {
Private T data;
Private exchanger<t> exchange;

Public MyThread (T data, exchanger<t> Exchange, String name) {
This.data = data;
This.exchange = Exchange;
SetName (name);
}

@Override
public void Run () {
System.out.println (GetName () + "is preparing to Exchange" + Data + ");
try {
Thread.Sleep ((int) (Math.random () * 10000));
T datas = exchange.exchange (data);
System.out.println (GetName () + "swap back for:" + datas);
} catch (Exception e) {
E.printstacktrace ();
}

}
}

}

Tool classes for threads (Exchange)

Related Article

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.