import java.util.concurrent.locks.*;
class Resource
{
Lock lock=new ReentrantLock();
Condition produce=lock.newCondition();
Condition consumer=lock.newCondition();
Object[] a=new Object[10];
int count,input,output;
public void pro(Object x)
{ lock.lock();
try
{
try
{
while (count==a.length)
{
produce.await();
}
}
catch (InterruptedException e1)
{
System.out.println();
}
a[input]=x;
if(++input==a.length)
input=0;
count++;
System.out.println(Thread.currentThread().getName()+"生产对象"+x);
consumer.signal();
}
finally
{
lock.unlock();
}
}
public Object con()
{
lock.lock();
try
{
try
{
while(count==0)
{consumer.await();}
}
catch (InterruptedException e2)
{
System.out.println();
}
Object y=a[output];
if(++output==a.length)
output=0;
count--;
produce.signal();
return y;
}
finally
{
lock.unlock();
}
}
}
class Make implements Runnable
{ Resource r=new Resource();
public Object makemake()
{
Object o=new Object();
return o;
}
public void run()
{
r.pro(makemake());
r.pro(makemake());
r.pro(makemake());
r.pro(makemake());
r.pro(makemake());
r.pro(makemake());
r.pro(makemake());
r.pro(makemake());
r.pro(makemake());
r.pro(makemake());
}
}
class Spend implements Runnable
{
Resource r=new Resource();
public void run()
{
for (int x =0;x<10 ;x++ )
{
System.out.println(Thread.currentThread().getName()+"消费对象"+r.con());
}
}
}
class ProConTest
{
public static void main(String[] args)
{
Spend s=new Spend();
Make m=new Make();
Thread t1=new Thread(m);
Thread t2=new Thread(s);
t1.start();
t2.start();
}
}