假设有一个仓库,生产者生产产品放入仓库,消费者从仓库消费产品,有多个生产者和消费者同时进行操作,那么这里我们就用到多线程来解决问题了,生产者消费者问题是一个典型的线程共享资源的应用,下面我们就来看看具体实现方法:
为了便于理解,下面是一个简单的模型设计:
首先我们要有生产和消费的物品,必须有个产品类,这里我们将产品定为手机,为了代码简单,此处我只定义一个编号:
/**
* 产品类(手机)
* @author HP
*
*/
public class Mobile {
private int num;
public Mobile(int num) {
super();
this.num = num;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
然后,我们要有一个仓库类用来存放手机,因为仓库容量是有限的,这里我用一个数组来进行存放,并且一旦索引大于数组长度,则显示仓库已满,使用wait()使其暂停生产手机,等待消费者消费,反之亦然:
/**
* 仓库类
* @author HP
*
*/
public class Storage {
/**存储产品的容器*/
private Mobile[] list = new Mobile[10];
/**用于表示生产或消费到的产品索引*/
private int index;
public synchronized void push(Mobile m){
while(index == list.length){
try {
System.out.println("仓库已满,等待消费...");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//通知消费者消费
notifyAll();
list[index++] = m;
}
public synchronized Mobile pop(){
while(index == 0){
try {
System.out.println("仓库已空,等待生产。。。");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//通知生产者生产
notifyAll();
index--;
Mobile m = list[index];
return m;
}
public synchronized int size(){
return index;
}
}
接下来就是生产者和消费者类了,其必须实现Runnable接口表明其为多线程,实现反复操作:
/**
* 生产者
* @author HP
*/
public class Product implements Runnable{
private Storage s;
public Product(Storage s) {
super();
this.s = s;
}
@Override
public void run() {
int i = 0;
while(true){
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
Mobile m = new Mobile(i);
s.push(m);
System.out.println("生产者"+Thread.currentThread().getName()+"生产一部手机:"+i+".............库存........"+s.size());
i++;
}
}
}
/**
* 消费者
* @author HP
*/
public class Consumer implements Runnable{
private Storage s;
public Consumer(Storage s) {
super();
this.s = s;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Mobile m = s.pop();
System.out.println("消费者"+Thread.currentThread().getName()+"消费一部手机。。。。"+m.getNum()+"........库存....."+s.size());
}
}
}
其中我加入了sleep休眠避免执行过快不好观察变化,如果想让生产者生产快点就休眠时间比消费者短点,如果想让生产比消费慢,就让生产者休眠时间长点。下面我们看看运行结果为不间断生产(这里就不剪视频了,放两张图片省时省力):
但是此处我还有一个需要完善的功能,因为线程的不确定性,即使我加了锁,但由于是多个生产者和消费者共用仓库导致库存量可能没法及时更新,不知道应该怎样完善,希望各路大神能帮我解答困惑,万分感谢!