码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-03-03 14:08:54      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:catch   rod   trace   import   一个   port   消费者   exchanger   理解   

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

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

代码如下:

package exchange;

import java.util.concurrent.Exchanger;

public class ExchangerDemo {

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

    //生产者
    static class Producer extends Thread {

        private Exchanger<String> exchanger;

        public Producer(Exchanger<String> 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<String> exchanger;

        public Costomer(Exchanger<String> 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();
    }
}

  

 

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

标签:catch   rod   trace   import   一个   port   消费者   exchanger   理解   

原文地址:https://www.cnblogs.com/eviltuzki/p/8496305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!