生产者和消费者设计模式代码实例:
产品库和get/set方法:
class SyncStack {
int index = 0;
WoTou[] wt = new WoTou[5];
public synchronized void push(WoTou w)
{
while(index == 5) //生产的数量控制,产品库存满了则等待消费
{
try
{
wait();
}catch(InterruptedException e) {
e.printStackTrace();
}
this.notifyAll();
}
wt[index] = w; //开始生产
System.out.println(Thread.currentThread().getName() +"生产了" + wt[index] +"号馒头");
index++;
this.notifyAll(); //通知等待的消费者消费
}
public synchronized void pop()
{
while(index == 0) //如果产品库中没有产品,则等待产品生产出来
{
try
{
//System.out.println("consumer wait");
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
notifyAll();
}
index--;
System.out.println(Thread.currentThread().getName() + "消费了第" + wt[index] + "个馒头");
}
}
消费者线程:
class Consumer implements Runnable
{
SyncStack s = null;
public Consumer(SyncStack s)
{
this.s = s;
}
public void run()
{
for(int i = 1; i<=10; ++i)
{
s.pop();
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
生产者线程:
class Producer implements Runnable
{
SyncStack s = null;
public Producer(SyncStack s)
{
this.s = s;
}
public void run()
{
for(int i = 1; i<=10; ++i)
{
s.push(new WoTou(i));
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
产品:
class WoTou{
int id = 0;
WoTou(int id)
{
this.id = id;
}
public String toString()
{
return "" + id;
}
}
主线程:
public class ProducerConsumer {
public static void main(String[ ] args) throws Exception {
SyncStack s = new SyncStack();
Consumer c1 = new Consumer(s);
Producer p1 = new Producer(s);
new Thread(c1).start(); //启动消费者线程
new Thread(p1).start(); //启动生产者线程
}
}