java.util.concurrent系列之--Exchanger

1、Exchanger 介紹

api: http://tool.oschina.net/apidocs/apidoc?api=jdk-zhjava

Exchanger類源於java.util.concurrent包,它能夠在兩個線程之間傳輸數據,Exchanger中的public V exchange(V x)方法被調用後等待另外一個線程到達交換點(若是當前線程沒有被中斷),而後將已知的對象傳給它,返回接收的對象。api

2、代碼講解

若是另一個線程已經在交換點等待,那麼恢復線程計劃並接收經過當前線程傳給的對象:ide

public class Car extends Thread {
    private Exchanger<String> exchanger;

    public Car(Exchanger<String> exchanger) {
        super();
        this.exchanger = exchanger;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + ": " + exchanger.exchange("Car"));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class Bike extends Thread {
    private Exchanger<String> exchanger;

    public Bike(Exchanger<String> exchanger) {
        super();
        this.exchanger = exchanger;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + ": " + exchanger.exchange("Bike"));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class Run {
    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();
        Car car = new Car(exchanger);
        Bike bike = new Bike(exchanger);
        car.start();
        bike.start();
        System.out.println("Main end!");
    }
}

輸出:this

Main end!
Thread-0: Bike
Thread-1: Car

從輸出的值能夠看到,兩個線程的值已經發生了交換。.net

3、參考文章

http://blog.csdn.net/sinat_36246371/article/details/53873693線程

相關文章
相關標籤/搜索