生产者和消费者模式

一、创建个生产者类

package consumerAndProducer;

/**
 * @author tanhw119214
 * @version JDK1.8.0_171
 * @date on  2018/8/2 16:57
 */
public class Producer implements Runnable{
    private DataStore m_data;
    public Producer(DataStore d) {
        m_data = d;
    }

    public void run() {
        System.out.print("producer thread run\n");
        int	 inPutData = 0;
        while (true) {
            m_data.producerData(inPutData++);
        }
    }
}

二、创建个消费者类

package consumerAndProducer;

/**
 * @author tanhw119214
 * @version JDK1.8.0_171
 * @date on  2018/8/2 16:56
 */
public class Consumer implements Runnable{
    private DataStore m_data;
    public Consumer(DataStore d) {
        m_data = d;
    }

    public void run() {
        System.out.print("consumer thread run\n");
        while (true) {
            m_data.consumerData();
        }
    }
}

三、创建个生产消费的类

package consumerAndProducer;

/**
 * @author tanhw119214
 * @version JDK1.8.0_171
 * @date on  2018/8/2 16:49
 */
public class DataStore {

        private int m_iData = 0;
        private boolean m_bSetData = true;

    /**
     * 生产
     * @param iInputData
     */
    public synchronized void producerData(int iInputData) {// 添加synchronized保证线程同步功能
            if (m_bSetData) {
                try {
                    this.wait(); //等待消费者消费
                } catch (InterruptedException e) {
                    System.out.print("InterrupExcepthion put data\n");
                }
            }
            System.out.print("producer: " + iInputData);
            m_iData = iInputData;
            m_bSetData = true;
            this.notify(); //继续生产

        }

    /**
     * 消费
     */
    public synchronized void consumerData() {
            if (!m_bSetData) {
                try {
                    this.wait(); //等待生产者产生数据,停止消费
                } catch (InterruptedException e) {
                    System.out.print("InterrupExcepthion get data\n");
                }
            }
            System.out.print("   consumer: " + m_iData + "\n");
            m_bSetData = false;
            this.notify(); //唤醒消费者线程,继续消费。
        }

}

四、创建一个Test运行类

package consumerAndProducer;

/**
 * @author tanhw119214
 * @version JDK1.8.0_171
 * @date on  2018/8/2 17:00
 */
public class Cmain {
    public static void main(String[] args) {
        DataStore dataStore = new DataStore();
        Consumer consumer = new Consumer(dataStore);
        Thread consumerThread = new Thread(consumer);
        consumerThread.start();



        Producer producer = new Producer(dataStore);
        Thread producerThread = new Thread(producer);
        producerThread.start();
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值