A synchronization point at which threads can pair and swap elements within pairs. Each thread presents some object on entry to the exchange method, matches with a partner thread, and receives its partner's object on return. An Exchanger may be viewed as a bidirectional form of a SynchronousQueue. Exchangers may be useful in applications such as genetic algorithms and pipeline designs.
Exchanger<V> V为可以交换的对象的类型;
Exchanger 它提供一个同步点,用于进行线程间成对配对及交换数据,两个线程通过exchange方法交换数据,如果第一个线程先执行exchange方法,它会一直等待第二个线程也执行exchange,当两个线程都到达同步点时,这两个线程就可以交换数据,将本线程生产出来的数据传递给对方。因此使用Exchanger的重点是成对的线程使用exchange()方法,当有一对线程达到了同步点,就会进行交换数据。因此该工具类的线程对象是成对的。
public class Exchange_Thread { public static void main(String[] args) { ExecutorService executorSer = Executors.newCachedThreadPool(); final Exchanger<String> exchanger = new Exchanger<String>(); executorSer.execute(new Runnable() { String data = "Lebron James"; public void run() { System.out.println(Thread.currentThread().getName() + "请在交易截止日前交易走:"+ data); try { Thread.sleep((long)(Math.random()*100)); String data1 = (String) exchanger.exchange(data); System.out.println(Thread.currentThread().getName() + "交易得到:"+ data1); } catch (InterruptedException e) { e.printStackTrace(); } } }); executorSer.execute(new Runnable() { String data = "Anderson, Gerdon and some cash"; public void run() { System.out.println(Thread.currentThread().getName() + "请在交易截止日前交易走:"+ data); try { Thread.sleep((long)(Math.random()*100)); String data1 = (String) exchanger.exchange(data); System.out.println(Thread.currentThread().getName() + "交易得到:"+ data1); } catch (InterruptedException e) { e.printStackTrace(); } } }); executorSer.execute(new Runnable() { String data = "Stephen Curry"; public void run() { System.out.println(Thread.currentThread().getName() + "请在交易截止日前交易走:"+ data); try { Thread.sleep((long)(Math.random()*100)); String data1 = (String) exchanger.exchange(data); System.out.println(Thread.currentThread().getName() + "交易得到:"+ data1); } catch (InterruptedException e) { e.printStackTrace(); } } }); executorSer.execute(new Runnable() { String data = "Paul George"; public void run() { System.out.println(Thread.currentThread().getName() + "请在交易截止日前交易走:"+ data); try { Thread.sleep((long)(Math.random()*100)); String data1 = (String) exchanger.exchange(data); System.out.println(Thread.currentThread().getName() + "交易得到:"+ data1); } catch (InterruptedException e) { e.printStackTrace(); } } }); executorSer.shutdown(); } }
转载请标明出处:Exchanger简单示例
文章来源: Exchanger简单示例