最近看了一段关于多线程生产者消费者模式的视频,觉得挺好自己就做了一些记录,以便加强记忆,并且跟各位分享下自己的体会,有不足之处请大家指正。
(1)首先是单线程模式下的生产者消费者模式。
我的理解是:生产者消费者模式包含三个对象,生产者、消费者、资源对象。其中资源对象主要是提供资源供生产者和消费者使用,生产者就是不断生产对象(线程实现),消费者就是不断进行消费(线程实现)。
下面是工程结构:
Resource.java代码实现:
public class Resource {
//商品名称
private String name;
//商品编号
private int id=1;
//是否有商品:初始化是无商品的状态
private boolean hasGoods = false;
//生产方法
public synchronized void set(String name){
//如果有商品,那么就wait一下
if(hasGoods){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.name = name + "_" + id;
id++;
System.out.println("生产线程名称"+Thread.currentThread().getName()+"已生产商品名称是"+this.name);
hasGoods = true;
//本意是通知消费线程来消费
notify();
}
//消费方法
public synchronized void out(){
//如果没有商品,那么就等待一下
if(!hasGoods){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("消费线程名称"+Thread.currentThread().getName()+"已消费消费商品名称是"+this.name);
hasGoods = false;
//本意是通知生产线程来生产
notify();
}
}
Productor.java代码实现:
public class Productor implements Runnable{
//持有资源类引用
private Resource resource ;
public Productor(Resource resource){
this.resource = resource;
}
//
@Override
public void run() {
while(true){
resource.set("iphone7s");
}
}
}
Customer.java 代码实现:
public class Customer implements Runnable{
//持有资源类引用
private Resource resource ;
public Customer(Resource resource){
this.resource = resource;
}
//
@Override
public void run() {
while(true){
resource.out();
}
}
}
测试类ProductAndCustom.java代码实现:
public class ProductAndCustom {
public static void main(String[] args) {
//创造一个资源类
Resource resource = new Resource();
//启动生产线程来生产
new Thread(new Productor(resource)).start();
//启动消费线程来消费
new Thread(new Customer(resource)).start();
}
}
以上就是单线程生产者消费者模式的代码实现,经测试,在单线程状态下没有问题,但是在多线程情况下回有问题,下一篇博客中会在分析下这个问题。