记得第一次做java的题的时候,看到“写出生产者消费者问题”,还以为是和工厂模式有关系。现在想想也是被雷倒了。
java的生产者消费者问题其实是讲多线程并发操作同一资源缓冲区,当资源缓冲区满的时候,线程继续添加数据,则应该使其等待,有空间时再发消息通知;当资源缓冲区没有资源,线程继续取数据时,应该使其等待,有资源是再发消息通知;
先看一下运行截图:
以下是代码:
Main.java:(主类)
package com.vrinux.setandget;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建商店对象,并设置最大容量为10;
Store store = new Store(10);
//创建两个生产者;
Pro pro1 = new Pro(store);
Pro pro2 = new Pro(store);
//创建三个消费者;
Coner coner1 = new Coner(store);
Coner coner2 = new Coner(store);
Coner coner3 = new Coner(store);
//启动线程;
pro1.start();
pro2.start();
coner1.start();
coner2.start();
coner3.start();
}
}
Store.java:(商店类)
package com.vrinux.setandget;
public class Store {
//静态变量,商店的最大存储值;
private final int max;
//商店存储的初始值;为0;
private int count;
//构造器;
public Store(int max) {
this.max = max;
this.count = 0;
}
//进货的方法,【注意】要用synchronized修饰,这是同步锁,
public synchronized void add() {
//判断商店存储数量是否已满;是则让生产者等待;
while(count>=max){
System.out.println("仓库已满,请稍再后入货~");
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//没有满,则进货1;
count += 1;
//打印当前库存;
System.out.println("当前库存为"+count);
//通知所有生产者,可以进货;
this.notifyAll();
}
//消费的方法,【注意】要用synchronized修饰,这是同步锁,
public synchronized void remove() {
//判断商店库存是否没货,是则让消费者等待;
while(count<=0){
System.out.println("仓库缺货,请稍后再取货~");
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//否则,消费1;
count -= 1;
//打印库存;
System.out.println("当前库存为"+count);
//通知所有消费者来消费;
this.notifyAll();
}
}
Pro.java:(生产者)
package com.vrinux.setandget;
public class Pro extends Thread{
private Store store;
public Pro(Store store){
this.store = store;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
//向store进货,并休眠;
store.add();
try {
Thread.sleep(610);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Coner.java:(消费者)
package com.vrinux.setandget;
public class Coner extends Thread {
private Store store;
public Coner(Store store) {
this.store = store;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
//从store消费,并休眠;
store.remove();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
原文地址:http://blog.csdn.net/vrinux/article/details/44996545