package Thread;
public class ProducerConsumer 

{
public static void main(String[] args) 
{
SynchronizedStack ss = new SynchronizedStack();
Producer p = new Producer(ss); //产生一个生产者
Consumer c = new Consumer(ss); //产生一个消费者
new Thread(p).start(); //启动生产者线程
new Thread(c).start(); //启动消费者线程
}
}
class Bread //定义生产面包

{
int id;
Bread(int id)
{
this.id = id;
}
public String toString() //重写toString方法
{
return "bread :" + id;
}
}
class SynchronizedStack //定义一个盛面包的容器

{
int index = 0;
Bread[] bread = new Bread[6];
public synchronized void putIn(Bread bread) // 放进方法
{
while(index == this.bread.length)
{
try 
{
this.wait(); // 只针对synchronized
//Object对象的wait()方法,表示调用当前对象的wait()方法,运行当前对象的此方法的线程等待,直到被notify()唤醒
}
catch (InterruptedException e) 
{
e.printStackTrace();
}
}
this.notify(); //唤醒一个wait的线程
// this.notifyAll();//唤醒所有wait的线程
this.bread[index] = bread;
index ++;
}
public synchronized Bread putOut() // 拿出方法
{
while(index == 0)
{
try 
{
this.wait();
}
catch (InterruptedException e) 
{
e.printStackTrace();
}
}
this.notify(); //唤醒一个wait的线程
// this.notifyAll();//唤醒所有wait的线程
index --;
return bread[index];
}
}
class Producer implements Runnable

{
SynchronizedStack ss = null;
Producer(SynchronizedStack ss)
{
this.ss = ss;
}
public void run() 
{
for(int i=0;i<30;i++)
{
Bread bread = new Bread(i);
ss.putIn(bread);
System.out.println("生产了 :" + bread);
try
{
// Thread.sleep(1000);
Thread.sleep((int)Math.random() * 1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable

{
SynchronizedStack ss = null;
Consumer(SynchronizedStack ss)
{
this.ss = ss;
}
public void run() 
{
for(int i=0;i<30;i++)
{
Bread bread = ss.putOut();
System.out.println("消费了 :" + bread);
try
{
// Thread.sleep(1000);
Thread.sleep((int)Math.random() * 1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
生产者消费者模式
本文介绍了一个使用Java实现的生产者消费者模式案例。通过一个同步栈作为共享资源,生产者线程不断生产面包并放入栈中,消费者线程从栈中取出面包进行消费。该案例演示了如何使用synchronized关键字来实现线程间的同步,并通过wait和notify方法控制生产者与消费者的交互。
1218

被折叠的 条评论
为什么被折叠?



