Exchanger

作者: uriah | 来源:发表于2016-10-16 21:26 被阅读0次

    java.util.concurrent.Exchanger 是用来支持两个线程之间交换数据,不支持更多线程。class represents a kind of rendezvous point where two threads can exchange objects. Here is an illustration of this mechanism:

    Two threads exchanging objects via an Exchanger.

    当线程A调用exchange()方法时,将会阻塞,直到另一个线程也调用此方法。以一个线程安全的方式交换数据。

    例子如下

    Exchanger exchanger = new Exchanger();

    ExchangerRunnable exchangerRunnable1 =

    new ExchangerRunnable(exchanger, "A");

    ExchangerRunnable exchangerRunnable2 =

    new ExchangerRunnable(exchanger, "B");

    new Thread(exchangerRunnable1).start();

    new Thread(exchangerRunnable2).start();


    public class ExchangerRunnable implements Runnable{

    Exchanger exchanger = null;

    Object    object    = null;

    public ExchangerRunnable(Exchanger exchanger, Object object) {

    this.exchanger = exchanger;

    this.object = object;

    }

    public void run() {

    try {

    Object previous = this.object;

    this.object = this.exchanger.exchange(this.object);

    System.out.println(

    Thread.currentThread().getName() +

    " exchanged " + previous + " for " + this.object

    );

    } catch (InterruptedException e) {

    e.printStackTrace();

    }

    }

    }

    相关文章

      网友评论

          本文标题:Exchanger

          本文链接:https://www.haomeiwen.com/subject/aokayttx.html