import java.util.concurrent.locks.*;
class Clothes{
private String name;
private double price;
private Clothes[] arr = new Clothes[100];
private Lock lock = new ReentrantLock();
private Condition pro = lock.newCondition();
private Condition con = lock.newCondition();
private int propointer;
private int conpointer;
private int count;
public Clothes(){}
public Clothes(String name,double price){
this.name = name;
this.price = price;
}
public void produce(){
lock.lock();
try{
while(count==arr.length){
try{pro.await();}catch(InterruptedException e){e.printStackTrace();}
}
arr[propointer] = new Clothes("衬衣",99.99);
System.out.println(Thread.currentThread().getName()+"...生产了..."+arr[propointer]+"..."+count);
count++;
if(++propointer==arr.length)
propointer = 0;
con.signal();
}
finally{
lock.unlock();
}
}
public void consume(){
lock.lock();
try{
while(count==0){
try{con.await();}catch(InterruptedException e){e.printStackTrace();}
}
Clothes yifu = arr[conpointer];
System.out.println(Thread.currentThread().getName()+"...消费了..."+yifu);
count--;
if(++conpointer==arr.length)
conpointer = 0;
pro.signal();
}
finally{
lock.unlock();
}
}
public String toString(){
return name+","+price;
}
}
class Producer implements Runnable{
private Clothes clo;
public Producer(Clothes clo){
this.clo = clo;
}
public void run(){
while(true){
clo.produce();
}
}
}
class Consumer implements Runnable{
private Clothes clo;
public Consumer(Clothes clo){
this.clo = clo;
}
public void run(){
while(true){
clo.consume();
}
}
}
class test{
public static void main(String[] args){
Clothes clo = new Clothes();
Producer producer = new Producer(clo);
Consumer consumer = new Consumer(clo);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(producer);
Thread t3 = new Thread(consumer);
Thread t4 = new Thread(consumer);
t1.start();
t2.start();
t3.start();
t4.start();
}
}