多线程模拟producer和consumer问题

package com.dijkstra;

public class Buffer {

 private int contents;//
 private boolean avaliable = false;

 public synchronized int get() {

  while (!avaliable) {
   try {
    this.wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  int value = contents;
  avaliable = false;
  System.out.println("取出:\t" + contents);
  this.notifyAll();
  return value;
 }

 public synchronized void put(int value) {

  while (avaliable) {
   try {
    this.wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  contents = value;
  avaliable = true;
  System.out.println("存入\t" + contents);
  this.notifyAll();

 }
}

=======================================================

package com.dijkstra;

public class Producer extends Thread {

 private Buffer buf;
 private String name;

 public Producer(Buffer buf, String name) {
  super();
  this.buf = buf;
  this.name = name;
 }

 public void run() {

  for (int i = 0;;) {
   buf.put(i);
   System.out.println("生产者" + name + "生产" + i++);
   try {
    Thread.sleep(500);

   } catch (InterruptedException e) {
    // TODO: handle exception
    e.printStackTrace();
   }
  }

 }
}

===================================================

package com.dijkstra;

public class Consumer extends Thread {
 private Buffer buf;
 private int number;

 public Consumer(Buffer buf, int number) {
  // super();
  this.buf = buf;
  this.number = number;
 }

 public void run() {

  for (;;) {
   //
   int v = buf.get();
   System.out.println("消费者" + number + "消费" + v);
  }

 }
}

===============================================================

package com.dijkstra;

public class ProducerConsumerProblem {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  Buffer buf = new Buffer();
  new Producer(buf, "\tprducer1\t").start();

  new Consumer(buf, 1).start();
  new Consumer(buf, 2).start();
  new Consumer(buf, 3).start();

 }

}

=================================================

运行结果:

存入 0
生产者 prducer1 生产0
取出: 0
消费者2消费0
存入 1
生产者 prducer1 生产1
取出: 1
消费者3消费1
存入 2
生产者 prducer1 生产2
取出: 2
消费者1消费2
存入 3
生产者 prducer1 生产3
取出: 3
消费者1消费3
存入 4
取出: 4
消费者2消费4
生产者 prducer1 生产4
存入 5
生产者 prducer1 生产5
取出: 5
消费者2消费5....................

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值