import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//缓冲池(共享区)
class Pool
{
final Lock lock = new ReentrantLock();// 创建互斥锁
// 分别将两个监听器绑定到同一个锁上。
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
// 商品数组对象
final Goods[] items = new Goods[Goods.MAX_SIZE];
// 下标,计数器
int pro, con, count;
// 封装生产者方法
public void product(Goods x) throws InterruptedException
{
lock.lock();
try
{
while (count == Goods.MAX_SIZE)
{
notFull.await();
}
items[pro] = x;
System.out.println("生产\"" + ++count + "\"号商品--名称:"
+ items[pro].getName() + "--价格:" + items[pro].getPrice());
if (++pro == Goods.MAX_SIZE)
{
pro = 0;
}
notEmpty.signal();
}
finally
{
lock.unlock();
}
}
// 封装消费者方法
public Goods consume() throws InterruptedException
{
lock.lock();
try
{
while (count == 0)
{
notEmpty.await();
}
Goods goods = items[con];
System.out.println("消费\"" + --count + "\"号商品--名称:"
+ items[con].getName() + "--价格:" + items[con].getPrice());
if (++con == Goods.MAX_SIZE)
{
con = 0;
}
notFull.signal();
return goods;
}
finally
{
lock.unlock();
}
}
}
// 生产者
class Producter implements Runnable
{
private Pool p;
private Goods g;
Producter(Pool p, Goods g)
{
this.p = p;
this.g = g;
}
public void run()
{
while (true)
{
try
{
p.product(g);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// 消费者
class Consumer implements Runnable
{
Pool p;
Goods g;
Consumer(Pool p, Goods g)
{
this.p = p;
this.g = g;
}
public void run()
{
while (true)
{
try
{
p.consume();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// 商品
class Goods
{
static final int MAX_SIZE = 100;
private String name;
private int price;
Goods(String name, int price)
{
this.name = name;
this.price = price;
}
public String getName()
{
return name;
}
public int getPrice()
{
return price;
}
}
public class Producter_consumer
{
public static void main(final String[] args)
{
// 定义商品对象
Goods bread = new Goods("面包", 10);
// 创建资源
Pool resource = new Pool();
// 创建线程任务,生产和消费
Producter productTask = new Producter(resource, bread);
Consumer consumeTask = new Consumer(resource, bread);
// 创建线程,两个生产者线程,两个消费者线程
Thread t0 = new Thread(productTask);
Thread t1 = new Thread(productTask);
Thread t2 = new Thread(consumeTask);
Thread t3 = new Thread(consumeTask);
// 开启线程
t0.start();
t1.start();
t2.start();
t3.start();
}
}