一、创建个生产者类
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();
}
}