java concurrent 之 semaphore

java concurrent 之 semaphore

java.util.concurrent.Exchanger类表示一种会聚点,其中两个线程可以交换对象。 这是一个这个机制的例证

java concurrent 之 semaphore_第1张图片
image

通过两种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();
        }
    }
}

输出


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

你可能感兴趣的:(java concurrent 之 semaphore)