多线程-java.util.concurrent.Exchanger

    Exchanger的功能可以使2个线程之间传输数据,它比生产者消费者模式使用的wait/notify要更加方便,类Exchanger中的exchange()方法具有阻塞的特色,也就是此方法被调用后等待其他线程来取得数据,如果没有其他线程取得数据,则一直阻塞等待。Exchanger主要有两个方法 :exchanger(V x)exchanger(V x, long timeout, TimeUnit unit)。下面看看一个很简单的示例:

public class ExchangerTest {
    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();
        new Thread(new WorkA(exchanger)).start();
        new Thread(new WorkB(exchanger)).start();
    }
}

class WorkA extends Thread{
    private Exchanger<String> exchanger;

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

    @Override
    public void run() {
        try {
            System.out.println("WorkerA想要给WorkerB" + exchanger.exchange("一个比特币"));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class WorkB extends Thread{
    private Exchanger<String> exchanger;

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

    @Override
    public void run() {
        try {
            System.out.println("WorkerB想要给WorkerA" + exchanger.exchange("1w美金"));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

    两个线程通过exchange交换数据。这个使用比较简单。

参考:

  【1】《Java并发编程实战》,高洪岩

      【2】https://www.cnblogs.com/davidwang456/p/4179488.html

posted @ 2021-02-21 13:46  寻找风口的猪  阅读(116)  评论(0编辑  收藏  举报