Exchanger

时间:2020-01-09 10:36:26  来源:igfitidea点击:

" java.util.concurrent.Exchanger"类表示一种交汇点,两个线程可以在该交汇点交换对象。

交换对象是通过两种" 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();

这是ExchangerRunnable代码:

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();
        }
    }
}

此示例将输出以下内容:

Thread-0 exchanged A for B
Thread-1 exchanged B for A