class CharCon
{
private char[] data = new char[5];
private int cnt = 0;
public synchronized void push(char ch)
{
while (cnt == data.length)
{
try
{
this.wait();
}
catch (Exception e)
{
}
}
this.notify();
data[cnt] = ch;
cnt++;
System.out.printf("%s正在生产第%d 产品%c/n", Thread.currentThread().getName(), cnt, ch);
}
public synchronized char pop()
{
while (cnt == 0)
{
try
{
this.wait();
}
catch (Exception e)
{
}
}
this.notify();
char ch;
ch = data[cnt-1];
System.out.printf("%s正在消费第%d 产品%c/n", Thread.currentThread().getName(), cnt, ch);
cnt--;
return ch;
}
}
class Produce implements Runnable
{
int i;
char ch;
private CharCon ss = null;
public Produce(CharCon a)
{
this.ss = a;
}
public void run()
{
for (i = 1; i <= 20; i++)
{
try
{
Thread.sleep(100);
}
catch (Exception e)
{
}
ch = (char)('a' + i);
ss.push(ch);
}
}
}
class Consume implements Runnable
{
int i;
private CharCon ss = null;
public Consume(CharCon a)
{
this.ss = a;
}
public void run()
{
for (i = 1; i <= 20; i++)
{
try
{
Thread.sleep(100);
}
catch (Exception e)
{
}
ss.pop();
}
}
}
class ProduceAndConsume
{
public static void main(String[] args)
{
CharCon ss = new CharCon();
Produce p = new Produce(ss);
Thread t = new Thread(p);
t.setName("生产线程1:");
t.start();
Consume c = new Consume(ss);
Thread t1 = new Thread(c);
t1.setName("消费线程2:");
t1.start();
}
}