学习了解 Exchanger - 实现生产者消费者模型

例子很简单 Exchanger可以理解为消息队列或者说是一个通信管道,从一边拿到消息,另外一边进行消费。

不过这个是同步实现的,消费者在exchange之前,生产者一直处于等待状态,而不是一直生产。

代码如下:

package exchange;

import java.util.concurrent.Exchanger;

public class ExchangerDemo {

    final static Exchanger exchanger = new Exchanger<>();

    //生产者
    static class Producer extends Thread {

        private Exchanger exchanger;

        public Producer(Exchanger exchanger) {

            this.exchanger = exchanger;
        }

        public void run() {
            for (int i = 1; i <= 100; i++) {
                try {
                    String message = "有价值的消息" + i;
                    System.out.println("生产者准备发送:"  + message);
                    String result = exchanger.exchange(message);
                    System.out.println("生产者收到:"+result);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    //消费者
    static class Costomer extends Thread {
        private Exchanger exchanger;

        public Costomer(Exchanger exchanger) {
            this.exchanger = exchanger;
        }

        public void run() {
            //消费者
            int count = 1;
          while (true){
              String message = "消费者收到第"+(count++) + "条消息";
              try {
                  Thread.sleep(100);
                  String exchange = exchanger.exchange(message);
                  System.out.println(message + ",消息内容为:" + exchange);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
        }

    }

    public static void main(String[] args) {
        new Producer(exchanger).start();
        new Costomer(exchanger).start();
    }
}

  

 

转载于:https://www.cnblogs.com/eviltuzki/p/8496305.html

你可能感兴趣的:(学习了解 Exchanger - 实现生产者消费者模型)