您的位置:首页 > 编程语言 > Java开发

经典问题生产者与消费者java并发线程模拟实现

2016-09-19 15:49 691 查看
生产者与消费者问题是操作系统中一个基础的问题。大致描述如下:生产者生产产品,消费者消费该产品。生产者只有等待消费者将产品消费完之后才能继续生产下一个产品,而消费者只有等带生产者生产完才能进行消费。生产者依赖于消费者,消费者依赖于生产者。

将该问题放到Java中来实现就是一个并发的多线程的问题,为了保证数据的完整性,需要借助线程同步的synchronized,用于控制数据同步时的一致。

同时为了保证生产者和消费者之间有序的进行需要使用wait和notify来实现线程的等待和唤醒操作。

直接贴代码,有问题,欢迎交流

/**
* 生产者消费者模拟
* Created by Gsr on 2016/9/19 0019.
*/
public class ProducerConsumer {
public static void main(String[] args) {
Product info = new Product();
Producer pro = new Producer(info);
Consumer con = new Consumer(info);
new Thread(pro).start();//生产者先起动,用于生产
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(con).start();
}
}

/**
* 产品信息
*/
class Product {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
private String name = "生产者";

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

private String content = "产品0";
private boolean flag = true;//true表示正在生产,false表示可以消费,开始的时候必须置为true表示正在生产,还不能消费

public synchronized void set(String name, String content) {//用于模拟生产过程
while (!flag) {//表示还没有被取走,继续等待
try {
super.wait();//等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setName(name);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setContent(content);
System.out.println("生产过程:"+this.getName()+" --> "+this.getContent());
flag = false;//改变标志位表示可以取走
super.notify();
}

public synchronized void get() {//将产品取出,用于模拟消费过程
while (flag) {//表示还没有生产好,继续等待
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费过程: "+this.getName() + " --> " + this.getContent());
flag = true;//表示可以生产
super.notify();
}
}

/**
* 生产者
*/
class Producer implements Runnable {
private Product info = null;//保存Info引用
public Producer(Product info) {
this.info = info;
}
@Override
public void run() {
boolean flag = true;
while(true) {
if (flag) {
this.info.set("生产--1", "产品1");
flag = false;
} else {
this.info.set("生产--2", "产品2");
flag = true;
}
}
}
}

/**
* 消费者
*/
class Consumer implements Runnable{
private Product info = null;
public Consumer(Product info){
this.info = info;
}
@Override
public void run() {
while(true)
this.info.get();
}
}


目前研究于Spark与Hadoop,群QQ号:521066396(spark,hadoop交流群),欢迎加入共同学习,一起进步~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息