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)