ProduceAndConsume

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();
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值